*** empty log message ***
[gnus] / lisp / nnmail.el
1 ;;; nnmail.el --- mail support functions for the Gnus mail backends
2 ;; Copyright (C) 1995,96,97 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 (require 'custom)
33
34 (defgroup gnus-mail nil
35   "Mailreading.."
36   :group 'gnus)
37
38 (defcustom nnmail-split-methods
39   '(("mail.misc" ""))
40   "Incoming mail will be split according to this variable.
41
42 If you'd like, for instance, one mail group for mail from the
43 \"4ad-l\" mailing list, one group for junk mail and one for everything
44 else, you could do something like this:
45
46  (setq nnmail-split-methods
47        '((\"mail.4ad\" \"From:.*4ad\")
48          (\"mail.junk\" \"From:.*Lars\\\\|Subject:.*buy\")
49          (\"mail.misc\" \"\")))
50
51 As you can see, this variable is a list of lists, where the first
52 element in each \"rule\" is the name of the group (which, by the way,
53 does not have to be called anything beginning with \"mail\",
54 \"yonka.zow\" is a fine, fine name), and the second is a regexp that
55 nnmail will try to match on the header to find a fit.
56
57 The second element can also be a function.  In that case, it will be
58 called narrowed to the headers with the first element of the rule as
59 the argument.  It should return a non-nil value if it thinks that the
60 mail belongs in that group.
61
62 The last element should always have \"\" as the regexp.
63
64 This variable can also have a function as its value."
65   :group 'gnus-mail
66   :type '(choice (repeat :tag "Alist" (group (string :tag "Name") regexp))
67                  (function-item nnmail-split-fancy)
68                  (function :tag "Other")))
69
70 ;; Suggested by Erik Selberg <speed@cs.washington.edu>.
71 (defcustom nnmail-crosspost t
72   "If non-nil, do crossposting if several split methods match the mail.
73 If nil, the first match found will be used."
74   :group 'gnus-mail
75   :type 'boolean)
76
77 ;; Added by gord@enci.ucalgary.ca (Gordon Matzigkeit).
78 (defcustom nnmail-keep-last-article nil
79   "If non-nil, nnmail will never delete the last expired article in a directory.  
80 You may need to set this variable if other programs are putting
81 new mail into folder numbers that Gnus has marked as expired."
82   :group 'gnus-mail
83   :type 'boolean)
84
85 (defcustom nnmail-use-long-file-names nil
86   "If non-nil the mail backends will use long file and directory names.
87 If nil, groups like \"mail.misc\" will end up in directories like
88 \"mail/misc/\"."
89   :group 'gnus-mail
90   :type 'boolean)
91
92 (defcustom nnmail-default-file-modes 384
93   "Set the mode bits of all new mail files to this integer."
94   :group 'gnus-mail
95   :type 'integer)
96
97 (defcustom nnmail-expiry-wait 7
98   "*Expirable articles that are older than this will be expired.
99 This variable can either be a number (which will be interpreted as a
100 number of days) -- this doesn't have to be an integer.  This variable
101 can also be `immediate' and `never'."
102   :group 'gnus-mail
103   :type '(choice (const immediate)
104                  (integer :tag "days")
105                  (const never)))
106
107 (defcustom nnmail-expiry-wait-function nil
108   "Variable that holds function to specify how old articles should be before they are expired.
109   The function will be called with the name of the group that the
110 expiry is to be performed in, and it should return an integer that
111 says how many days an article can be stored before it is considered
112 \"old\".  It can also return the values `never' and `immediate'.
113
114 Eg.:
115
116 \(setq nnmail-expiry-wait-function
117       (lambda (newsgroup)
118         (cond ((string-match \"private\" newsgroup) 31)
119               ((string-match \"junk\" newsgroup) 1)
120               ((string-match \"important\" newsgroup) 'never)
121               (t 7))))"
122   :group 'gnus-mail
123   :type '(choice (const :tag "nnmail-expiry-wait" nil)
124                  (function :format "%v" nnmail-)))
125
126 (defcustom nnmail-spool-file 
127   (or (getenv "MAIL")
128       (concat "/usr/spool/mail/" (user-login-name)))
129   "Where the mail backends will look for incoming mail.
130 This variable is \"/usr/spool/mail/$user\" by default.
131 If this variable is nil, no mail backends will read incoming mail.
132 If this variable is a list, all files mentioned in this list will be
133 used as incoming mailboxes.
134 If this variable is a directory (i. e., it's name ends with a \"/\"),
135 treat all files in that directory as incoming spool files."
136   :group 'gnus-mail
137   :type 'file)
138
139 (defcustom nnmail-crash-box "~/.gnus-crash-box"
140   "File where Gnus will store mail while processing it."
141   :group 'gnus-mail
142   :type 'file)
143
144 (defcustom nnmail-use-procmail nil
145   "*If non-nil, the mail backends will look in `nnmail-procmail-directory' for spool files.
146 The file(s) in `nnmail-spool-file' will also be read."
147   :group 'gnus-mail
148   :type 'boolean)
149
150 (defcustom nnmail-procmail-directory "~/incoming/"
151   "*When using procmail (and the like), incoming mail is put in this directory.
152 The Gnus mail backends will read the mail from this directory."
153   :group 'gnus-mail
154   :type 'directory)
155
156 (defcustom nnmail-procmail-suffix "\\.spool"
157   "*Suffix of files created by procmail (and the like).
158 This variable might be a suffix-regexp to match the suffixes of
159 several files - eg. \".spool[0-9]*\"."
160   :group 'gnus-mail
161   :type 'regexp)
162
163 (defcustom nnmail-resplit-incoming nil
164   "*If non-nil, re-split incoming procmail sorted mail."
165   :group 'gnus-mail
166   :type 'boolean)
167
168 (defcustom nnmail-delete-file-function 'delete-file
169   "Function called to delete files in some mail backends."
170   :group 'gnus-mail
171   :type 'function)
172
173 (defcustom nnmail-crosspost-link-function 'add-name-to-file
174   "Function called to create a copy of a file.
175 This is `add-name-to-file' by default, which means that crossposts
176 will use hard links.  If your file system doesn't allow hard
177 links, you could set this variable to `copy-file' instead."
178   :group 'gnus-mail
179   :type '(radio (function-item add-name-to-file)
180                 (function-item copy-file)
181                 (function :tag "Other")))
182
183 (defcustom nnmail-movemail-program "movemail"
184   "*A command to be executed to move mail from the inbox.
185 The default is \"movemail\".
186
187 This can also be a function.  In that case, the function will be
188 called with two parameters -- the name of the INBOX file, and the file
189 to be moved to."
190   :group 'gnus-mail
191   :type 'string)
192
193 (defcustom nnmail-pop-password-required nil
194   "*Non-nil if a password is required when reading mail using POP."
195   :group 'gnus-mail
196   :type 'boolean)
197
198 (defcustom nnmail-read-incoming-hook 
199   (if (eq system-type 'windows-nt)
200       '(nnheader-ms-strip-cr)
201     nil)
202   "Hook that will be run after the incoming mail has been transferred.
203 The incoming mail is moved from `nnmail-spool-file' (which normally is
204 something like \"/usr/spool/mail/$user\") to the user's home
205 directory.  This hook is called after the incoming mail box has been
206 emptied, and can be used to call any mail box programs you have
207 running (\"xwatch\", etc.)
208
209 Eg.
210
211 \(add-hook 'nnmail-read-incoming-hook 
212            (lambda ()
213              (start-process \"mailsend\" nil 
214                             \"/local/bin/mailsend\" \"read\" \"mbox\")))
215
216 If you have xwatch running, this will alert it that mail has been
217 read.  
218
219 If you use `display-time', you could use something like this:
220
221 \(add-hook 'nnmail-read-incoming-hook
222           (lambda ()
223             ;; Update the displayed time, since that will clear out
224             ;; the flag that says you have mail.
225             (when (eq (process-status \"display-time\") 'run)
226               (display-time-filter display-time-process \"\"))))"
227   :group 'gnus-mail
228   :type 'hook)
229
230 ;; Suggested by Erik Selberg <speed@cs.washington.edu>.
231 (defcustom nnmail-prepare-incoming-hook nil
232   "Hook called before treating incoming mail.
233 The hook is run in a buffer with all the new, incoming mail."
234   :group 'gnus-mail
235   :type 'hook)
236
237 (defcustom nnmail-prepare-incoming-header-hook nil
238   "Hook called narrowed to the headers of each message.
239 This can be used to remove excessive spaces (and stuff like
240 that) from the headers before splitting and saving the messages."
241   :group 'gnus-mail
242   :type 'hook)
243
244 (defcustom nnmail-prepare-incoming-message-hook nil
245   "Hook called narrowed to each message."
246   :group 'gnus-mail
247   :type 'hook)
248
249 (defcustom nnmail-list-identifiers nil
250   "Regexp that matches list identifiers to be removed.
251 This can also be a list of regexps."
252   :group 'gnus-mail
253   :type '(choice regexp
254                  (repeat regexp)))
255
256 (defcustom nnmail-pre-get-new-mail-hook nil
257   "Hook called just before starting to handle new incoming mail."
258   :group 'gnus-mail
259   :type 'hook)
260
261 (defcustom nnmail-post-get-new-mail-hook nil
262   "Hook called just after finishing handling new incoming mail."
263   :group 'gnus-mail
264   :type 'hook)
265
266 (defcustom nnmail-split-hook nil
267   "Hook called before deciding where to split an article.
268 The functions in this hook are free to modify the buffer
269 contents in any way they choose -- the buffer contents are
270 discarded after running the split process."
271   :group 'gnus-mail
272   :type 'hook)
273
274 ;; Suggested by Mejia Pablo J <pjm9806@usl.edu>.
275 (defcustom nnmail-tmp-directory nil
276   "*If non-nil, use this directory for temporary storage when reading incoming mail."
277   :group 'gnus-mail
278   :type '(choice (const :tag "default" nil)
279                  (directory :format "%v")))
280
281 (defcustom nnmail-large-newsgroup 50
282   "*The number of the articles which indicates a large newsgroup.
283 If the number of the articles is greater than the value, verbose
284 messages will be shown to indicate the current status."
285   :group 'gnus-mail
286   :type 'integer)
287
288 (defcustom nnmail-split-fancy "mail.misc"
289   "Incoming mail can be split according to this fancy variable.
290 To enable this, set `nnmail-split-methods' to `nnmail-split-fancy'.
291
292 The format is this variable is SPLIT, where SPLIT can be one of
293 the following:
294
295 GROUP: Mail will be stored in GROUP (a string).  
296
297 \(FIELD VALUE SPLIT): If the message field FIELD (a regexp) contains
298   VALUE (a regexp), store the messages as specified by SPLIT.
299
300 \(| SPLIT...): Process each SPLIT expression until one of them matches.
301   A SPLIT expression is said to match if it will cause the mail
302   message to be stored in one or more groups.  
303
304 \(& SPLIT...): Process each SPLIT expression.
305
306 \(: FUNCTION optional args): Call FUNCTION with the optional args, in
307   the buffer containing the message headers.  The return value FUNCTION
308   should be a split, which is then recursively processed.
309
310 FIELD must match a complete field name.  VALUE must match a complete
311 word according to the `nnmail-split-fancy-syntax-table' syntax table.
312 You can use .* in the regexps to match partial field names or words.
313
314 FIELD and VALUE can also be lisp symbols, in that case they are expanded
315 as specified in `nnmail-split-abbrev-alist'.
316
317 GROUP can contain \\& and \\N which will substitute from matching
318 \\(\\) patterns in the previous VALUE.
319
320 Example:
321
322 \(setq nnmail-split-methods 'nnmail-split-fancy
323       nnmail-split-fancy
324       ;; Messages from the mailer daemon are not crossposted to any of
325       ;; the ordinary groups.  Warnings are put in a separate group
326       ;; from real errors.
327       '(| (\"from\" mail (| (\"subject\" \"warn.*\" \"mail.warning\")
328                           \"mail.misc\"))
329           ;; Non-error messages are crossposted to all relevant
330           ;; groups, but we don't crosspost between the group for the
331           ;; (ding) list and the group for other (ding) related mail.
332           (& (| (any \"ding@ifi\\\\.uio\\\\.no\" \"ding.list\")
333                 (\"subject\" \"ding\" \"ding.misc\"))
334              ;; Other mailing lists...
335              (any \"procmail@informatik\\\\.rwth-aachen\\\\.de\" \"procmail.list\")
336              (any \"SmartList@informatik\\\\.rwth-aachen\\\\.de\" \"SmartList.list\")
337              ;; People...
338              (any \"larsi@ifi\\\\.uio\\\\.no\" \"people.Lars Magne Ingebrigtsen\"))
339           ;; Unmatched mail goes to the catch all group.
340           \"misc.misc\"))"
341   :group 'gnus-mail
342   ;; Sigh!
343   :type 'sexp)
344
345 (defcustom nnmail-split-abbrev-alist
346   '((any . "from\\|to\\|cc\\|sender\\|apparently-to\\|resent-from\\|resent-to\\|resent-cc")
347     (mail . "mailer-daemon\\|postmaster\\|uucp"))
348   "Alist of abbreviations allowed in `nnmail-split-fancy'."
349   :group 'gnus-mail
350   :type '(repeat (cons :format "%v" symbol regexp)))
351
352 (defcustom nnmail-delete-incoming nil
353   "*If non-nil, the mail backends will delete incoming files after
354 splitting."
355   :group 'gnus-mail
356   :type 'boolean)
357
358 (defcustom nnmail-message-id-cache-length 1000
359   "*The approximate number of Message-IDs nnmail will keep in its cache.
360 If this variable is nil, no checking on duplicate messages will be
361 performed."
362   :group 'gnus-mail
363   :type '(choice (const :tag "disable" nil)
364                  (integer :format "%v")))
365
366 (defcustom nnmail-message-id-cache-file "~/.nnmail-cache"
367   "*The file name of the nnmail Message-ID cache."
368   :group 'gnus-mail
369   :type 'file)
370
371 (defcustom nnmail-treat-duplicates 'warn
372   "*If non-nil, nnmail keep a cache of Message-IDs to discover mail duplicates.
373 Three values are legal: nil, which means that nnmail is not to keep a
374 Message-ID cache; `warn', which means that nnmail should insert extra
375 headers to warn the user about the duplication (this is the default);
376 and `delete', which means that nnmail will delete duplicated mails.
377
378 This variable can also be a function.  It will be called from a buffer
379 narrowed to the article in question with the Message-ID as a
380 parameter.  It should return nil, `warn' or `delete'."
381   :group 'gnus-mail
382   :type '(choice (const :tag "off" nil)
383                  (const warn)
384                  (const delete)))
385
386 ;;; Internal variables.
387
388 (defvar nnmail-split-history nil
389   "List of group/article elements that say where the previous split put messages.")
390
391 (defvar nnmail-pop-password nil
392   "*Password to use when reading mail from a POP server, if required.")
393
394 (defvar nnmail-split-fancy-syntax-table nil
395   "Syntax table used by `nnmail-split-fancy'.")
396 (unless (syntax-table-p nnmail-split-fancy-syntax-table)
397   (setq nnmail-split-fancy-syntax-table
398         (copy-syntax-table (standard-syntax-table)))
399   ;; support the %-hack
400   (modify-syntax-entry ?\% "." nnmail-split-fancy-syntax-table))
401
402 (defvar nnmail-prepare-save-mail-hook nil
403   "Hook called before saving mail.")
404
405 (defvar nnmail-moved-inboxes nil
406   "List of inboxes that have been moved.")
407
408 (defvar nnmail-internal-password nil)
409
410 \f
411
412 (defconst nnmail-version "nnmail 1.0"
413   "nnmail version.")
414
415 \f
416
417 (defun nnmail-request-post (&optional server)
418   (mail-send-and-exit nil))
419
420 (defun nnmail-find-file (file)
421   "Insert FILE in server buffer safely."
422   (set-buffer nntp-server-buffer)
423   (erase-buffer)
424   (let ((format-alist nil)
425         (after-insert-file-functions nil))
426     (condition-case ()
427         (progn (insert-file-contents file) t)
428       (file-error nil))))
429
430 (defun nnmail-group-pathname (group dir &optional file)
431   "Make pathname for GROUP."
432   (concat
433    (let ((dir (file-name-as-directory (expand-file-name dir))))
434      ;; If this directory exists, we use it directly.
435      (if (or nnmail-use-long-file-names 
436              (file-directory-p (concat dir group)))
437          (concat dir group "/")
438        ;; If not, we translate dots into slashes.
439        (concat dir (nnheader-replace-chars-in-string group ?. ?/) "/")))
440    (or file "")))
441   
442 (defun nnmail-date-to-time (date)
443   "Convert DATE into time."
444   (condition-case ()
445       (let* ((d1 (timezone-parse-date date))
446              (t1 (timezone-parse-time (aref d1 3))))
447         (apply 'encode-time
448                (mapcar (lambda (el)
449                          (and el (string-to-number el)))
450                        (list
451                         (aref t1 2) (aref t1 1) (aref t1 0)
452                         (aref d1 2) (aref d1 1) (aref d1 0)
453                         (aref d1 4)))))
454     ;; If we get an error, then we just return a 0 time.
455     (error (list 0 0))))
456
457 (defun nnmail-time-less (t1 t2)
458   "Say whether time T1 is less than time T2."
459   (or (< (car t1) (car t2))
460       (and (= (car t1) (car t2))
461            (< (nth 1 t1) (nth 1 t2)))))
462
463 (defun nnmail-days-to-time (days)
464   "Convert DAYS into time."
465   (let* ((seconds (* 1.0 days 60 60 24))
466          (rest (expt 2 16))
467          (ms (condition-case nil (round (/ seconds rest))
468                (range-error (expt 2 16)))))
469     (list ms (condition-case nil (round (- seconds (* ms rest)))
470                (range-error (expt 2 16))))))
471
472 (defun nnmail-time-since (time)
473   "Return the time since TIME, which is either an internal time or a date."
474   (when (stringp time)
475     ;; Convert date strings to internal time.
476     (setq time (nnmail-date-to-time time)))
477   (let* ((current (current-time))
478          (rest (when (< (nth 1 current) (nth 1 time))
479                  (expt 2 16))))
480     (list (- (+ (car current) (if rest -1 0)) (car time))
481           (- (+ (or rest 0) (nth 1 current)) (nth 1 time)))))
482
483 ;; Function rewritten from rmail.el.
484 (defun nnmail-move-inbox (inbox)
485   "Move INBOX to `nnmail-crash-box'."
486   (if (not (file-writable-p nnmail-crash-box))
487       (gnus-error 1 "Can't write to crash box %s.  Not moving mail."
488                   nnmail-crash-box)
489     ;; If the crash box exists and is empty, we delete it.
490     (when (and (file-exists-p nnmail-crash-box)
491                (zerop (nnheader-file-size (file-truename nnmail-crash-box))))
492       (delete-file nnmail-crash-box))
493     (let ((inbox (file-truename (expand-file-name inbox)))
494           (tofile (file-truename (expand-file-name nnmail-crash-box)))
495           movemail popmail errors)
496       (if (setq popmail (string-match
497                          "^po:" (file-name-nondirectory inbox)))
498           (setq inbox (file-name-nondirectory inbox))
499         (setq movemail t)
500         ;; On some systems, /usr/spool/mail/foo is a directory
501         ;; and the actual inbox is /usr/spool/mail/foo/foo.
502         (when (file-directory-p inbox)
503           (setq inbox (expand-file-name (user-login-name) inbox))))
504       (if (member inbox nnmail-moved-inboxes)
505           ;; We don't try to move an already moved inbox.
506           nil
507         (if popmail
508             (progn
509               (when (and nnmail-pop-password
510                          (not nnmail-internal-password))
511                 (setq nnmail-internal-password nnmail-pop-password))
512               (when (and nnmail-pop-password-required
513                          (not nnmail-internal-password))
514                 (setq nnmail-internal-password
515                       (nnmail-read-passwd
516                        (format "Password for %s: "
517                                (substring inbox (+ popmail 3))))))
518               (message "Getting mail from post office ..."))
519           (when (or (and (file-exists-p tofile)
520                          (/= 0 (nnheader-file-size tofile)))
521                     (and (file-exists-p inbox)
522                          (/= 0 (nnheader-file-size inbox))))
523             (message "Getting mail from %s..." inbox)))
524         ;; Set TOFILE if have not already done so, and
525         ;; rename or copy the file INBOX to TOFILE if and as appropriate.
526         (cond 
527          ((file-exists-p tofile)
528           ;; The crash box exists already.
529           t)
530          ((and (not popmail)
531                (not (file-exists-p inbox)))
532           ;; There is no inbox.
533           (setq tofile nil))
534          (t
535           ;; If getting from mail spool directory, use movemail to move
536           ;; rather than just renaming, so as to interlock with the
537           ;; mailer.
538           (unwind-protect
539               (save-excursion
540                 (setq errors (generate-new-buffer " *nnmail loss*"))
541                 (buffer-disable-undo errors)
542                 (let ((default-directory "/"))
543                   (if (nnheader-functionp nnmail-movemail-program)
544                       (funcall nnmail-movemail-program inbox tofile)
545                     (apply 
546                      'call-process
547                      (append
548                       (list
549                        (expand-file-name nnmail-movemail-program
550                                          exec-directory)
551                        nil errors nil inbox tofile)
552                       (when nnmail-internal-password
553                         (list (prin1-to-string nnmail-internal-password)))))))
554                 (if (not (buffer-modified-p errors))
555                     ;; No output => movemail won
556                     (progn
557                       (unless popmail
558                         (set-file-modes tofile nnmail-default-file-modes))
559                       (push inbox nnmail-moved-inboxes))
560                   (set-buffer errors)
561                   ;; There may be a warning about older revisions.  We
562                   ;; ignore those.
563                   (goto-char (point-min))
564                   (if (search-forward "older revision" nil t)
565                       (progn
566                         (unless popmail
567                           (set-file-modes tofile nnmail-default-file-modes))
568                         (push inbox nnmail-moved-inboxes))
569                     ;; Probably a real error.
570                     (subst-char-in-region (point-min) (point-max) ?\n ?\  )
571                     (goto-char (point-max))
572                     (skip-chars-backward " \t")
573                     (delete-region (point) (point-max))
574                     (goto-char (point-min))
575                     (when (looking-at "movemail: ")
576                       (delete-region (point-min) (match-end 0)))
577                     (unless (yes-or-no-p
578                              (format "movemail: %s.  Continue? "
579                                      (buffer-string)))
580                       (error "%s" (buffer-string)))
581                     (setq tofile nil)))))))
582         (message "Getting mail from %s...done" inbox)
583         (and errors
584              (buffer-name errors)
585              (kill-buffer errors))
586         tofile))))
587
588 (defun nnmail-get-active ()
589   "Returns an assoc of group names and active ranges.
590 nn*-request-list should have been called before calling this function."
591   (let (group-assoc)
592     ;; Go through all groups from the active list.
593     (save-excursion
594       (set-buffer nntp-server-buffer)
595       (goto-char (point-min))
596       (while (re-search-forward 
597               "^\\([^ \t]+\\)[ \t]+\\([0-9]+\\)[ \t]+\\([0-9]+\\)" nil t)
598         ;; We create an alist with `(GROUP (LOW . HIGH))' elements.
599         (push (list (match-string 1)
600                     (cons (string-to-int (match-string 3))
601                           (string-to-int (match-string 2))))
602               group-assoc)))
603     group-assoc))
604
605 (defun nnmail-save-active (group-assoc file-name)
606   "Save GROUP-ASSOC in ACTIVE-FILE."
607   (when file-name
608     (nnheader-temp-write file-name
609       (nnmail-generate-active group-assoc))))
610
611 (defun nnmail-generate-active (alist)
612   "Generate an active file from group-alist ALIST."
613   (erase-buffer)
614   (let (group)
615     (while (setq group (pop alist))
616       (insert (format "%s %d %d y\n" (car group) (cdadr group)
617                       (caadr group))))))
618
619 (defun nnmail-get-split-group (file group)
620   "Find out whether this FILE is to be split into GROUP only.
621 If GROUP is non-nil and we are using procmail, return the group name
622 only when the file is the correct procmail file.  When GROUP is nil,
623 return nil if FILE is a spool file or the procmail group for which it
624 is a spool.  If not using procmail, return GROUP."
625   (if (or (eq nnmail-spool-file 'procmail)
626           nnmail-use-procmail)
627       (if (string-match (concat "^" (expand-file-name
628                                      (file-name-as-directory
629                                       nnmail-procmail-directory))
630                                 "\\([^/]*\\)" nnmail-procmail-suffix "$")
631                         (expand-file-name file))
632           (let ((procmail-group (substring (expand-file-name file)
633                                            (match-beginning 1)
634                                            (match-end 1))))
635             (if group 
636                 (if (string-equal group procmail-group)
637                     group
638                   nil)
639               procmail-group))
640         nil)
641     group))
642
643 (defun nnmail-process-babyl-mail-format (func artnum-func)
644   (let ((case-fold-search t)
645         start message-id content-length do-search end)
646     (goto-char (point-min))
647     (while (not (eobp))
648       (re-search-forward
649        "\f\n0, *unseen,+\n\\(\\*\\*\\* EOOH \\*\\*\\*\n\\)?" nil t)
650       (goto-char (match-end 0))
651       (delete-region (match-beginning 0) (match-end 0))
652       (narrow-to-region
653        (setq start (point))
654        (progn
655          ;; Skip all the headers in case there are more "From "s...
656          (or (search-forward "\n\n" nil t)
657              (search-forward-regexp "^[^:]*\\( .*\\|\\)$" nil t)
658              (search-forward "\1f\f"))
659          (point)))
660       (run-hooks 'nnmail-prepare-incoming-header-hook)
661       (goto-char (point-max))
662       ;; Find the Message-ID header.
663       (save-excursion
664         (if (re-search-backward "^Message-ID:[ \t]*\\(<[^>]*>\\)" nil t)
665             (setq message-id (buffer-substring (match-beginning 1)
666                                                (match-end 1)))
667           ;; There is no Message-ID here, so we create one.
668           (save-excursion
669             (when (re-search-backward "^Message-ID:" nil t)
670               (beginning-of-line)
671               (insert "Original-")))
672           (forward-line -1)
673           (insert "Message-ID: " (setq message-id (nnmail-message-id))
674                   "\n")))
675       ;; Look for a Content-Length header.
676       (if (not (save-excursion
677                  (and (re-search-backward 
678                        "^Content-Length:[ \t]*\\([0-9]+\\)" start t)
679                       (setq content-length (string-to-int
680                                             (buffer-substring 
681                                              (match-beginning 1)
682                                              (match-end 1))))
683                       ;; We destroy the header, since none of
684                       ;; the backends ever use it, and we do not
685                       ;; want to confuse other mailers by having
686                       ;; a (possibly) faulty header.
687                       (progn (insert "X-") t))))
688           (setq do-search t)
689         (widen)
690         (if (or (= (+ (point) content-length) (point-max))
691                 (save-excursion
692                   (goto-char (+ (point) content-length))
693                   (looking-at "\1f")))
694             (progn
695               (goto-char (+ (point) content-length))
696               (setq do-search nil))
697           (setq do-search t)))
698       (widen)
699       ;; Go to the beginning of the next article - or to the end
700       ;; of the buffer.  
701       (when do-search
702         (if (re-search-forward "^\1f" nil t)
703             (goto-char (match-beginning 0))
704           (goto-char (1- (point-max)))))
705       (delete-char 1)                   ; delete ^_
706       (save-excursion
707         (save-restriction
708           (narrow-to-region start (point))
709           (goto-char (point-min))
710           (nnmail-check-duplication message-id func artnum-func)
711           (setq end (point-max))))
712       (goto-char end))))
713
714 (defun nnmail-search-unix-mail-delim ()
715   "Put point at the beginning of the next Unix mbox message."
716   ;; Algorithm used to find the the next article in the
717   ;; brain-dead Unix mbox format:
718   ;;
719   ;; 1) Search for "^From ".
720   ;; 2) If we find it, then see whether the previous
721   ;;    line is blank and the next line looks like a header.
722   ;; Then it's possible that this is a mail delim, and we use it.
723   (let ((case-fold-search nil)
724         found)
725     (while (not found)
726       (if (not (re-search-forward "^From " nil t))
727           (setq found 'no)
728         (save-excursion
729           (beginning-of-line)
730           (when (and (or (bobp)
731                          (save-excursion
732                            (forward-line -1)
733                            (= (following-char) ?\n)))
734                      (save-excursion
735                        (forward-line 1)
736                        (while (looking-at ">From ")
737                          (forward-line 1))
738                        (looking-at "[^ \t:]+[ \t]*:")))
739             (setq found 'yes)))))
740     (beginning-of-line)
741     (eq found 'yes)))
742
743 (defun nnmail-search-unix-mail-delim-backward ()
744   "Put point at the beginning of the current Unix mbox message."
745   ;; Algorithm used to find the the next article in the
746   ;; brain-dead Unix mbox format:
747   ;;
748   ;; 1) Search for "^From ".
749   ;; 2) If we find it, then see whether the previous
750   ;;    line is blank and the next line looks like a header.
751   ;; Then it's possible that this is a mail delim, and we use it.
752   (let ((case-fold-search nil)
753         found)
754     (while (not found)
755       (if (not (re-search-backward "^From " nil t))
756           (setq found 'no)
757         (save-excursion
758           (beginning-of-line)
759           (when (and (or (bobp)
760                          (save-excursion
761                            (forward-line -1)
762                            (= (following-char) ?\n)))
763                      (save-excursion
764                        (forward-line 1)
765                        (while (looking-at ">From ")
766                          (forward-line 1))
767                        (looking-at "[^ \t:]+[ \t]*:")))
768             (setq found 'yes)))))
769     (beginning-of-line)
770     (eq found 'yes)))
771
772 (defun nnmail-process-unix-mail-format (func artnum-func)
773   (let ((case-fold-search t)
774         start message-id content-length end skip head-end)
775     (goto-char (point-min))
776     (if (not (and (re-search-forward "^From " nil t)
777                   (goto-char (match-beginning 0))))
778         ;; Possibly wrong format?
779         (error "Error, unknown mail format! (Possibly corrupted.)")
780       ;; Carry on until the bitter end.
781       (while (not (eobp))
782         (setq start (point)
783               end nil)
784         ;; Find the end of the head.
785         (narrow-to-region
786          start 
787          (if (search-forward "\n\n" nil t)
788              (1- (point))
789            ;; This will never happen, but just to be on the safe side --
790            ;; if there is no head-body delimiter, we search a bit manually.
791            (while (and (looking-at "From \\|[^ \t]+:")
792                        (not (eobp)))
793              (forward-line 1)
794              (point))))
795         ;; Find the Message-ID header.
796         (goto-char (point-min))
797         (if (re-search-forward "^Message-ID:[ \t]*\\(<[^>]+>\\)" nil t)
798             (setq message-id (match-string 1))
799           (save-excursion
800             (when (re-search-forward "^Message-ID:" nil t)
801               (beginning-of-line)
802               (insert "Original-")))
803           ;; There is no Message-ID here, so we create one.
804           (forward-line 1)
805           (insert "Message-ID: " (setq message-id (nnmail-message-id)) "\n"))
806         ;; Look for a Content-Length header.
807         (goto-char (point-min))
808         (if (not (re-search-forward
809                   "^Content-Length:[ \t]*\\([0-9]+\\)" nil t))
810             (setq content-length nil)
811           (setq content-length (string-to-int (match-string 1)))
812           ;; We destroy the header, since none of the backends ever 
813           ;; use it, and we do not want to confuse other mailers by
814           ;; having a (possibly) faulty header.
815           (beginning-of-line)
816           (insert "X-"))
817         (run-hooks 'nnmail-prepare-incoming-header-hook)
818         ;; Find the end of this article.
819         (goto-char (point-max))
820         (widen)
821         (setq head-end (point))
822         ;; We try the Content-Length value.  The idea: skip over the header
823         ;; separator, then check what happens content-length bytes into the
824         ;; message body.  This should be either the end ot the buffer, the
825         ;; message separator or a blank line followed by the separator.
826         ;; The blank line should probably be deleted.  If neither of the
827         ;; three is met, the content-length header is probably invalid.
828         (when content-length
829           (forward-line 1)
830           (setq skip (+ (point) content-length))
831           (goto-char skip)
832           (cond ((or (= skip (point-max))
833                      (= (1+ skip) (point-max)))
834                  (setq end (point-max)))
835                 ((looking-at "From ")
836                  (setq end skip))
837                 ((looking-at "[ \t]*\n\\(From \\)")
838                  (setq end (match-beginning 1)))
839                 (t (setq end nil))))
840         (if end
841             (goto-char end)
842           ;; No Content-Length, so we find the beginning of the next 
843           ;; article or the end of the buffer.
844           (goto-char head-end)
845           (or (nnmail-search-unix-mail-delim)
846               (goto-char (point-max))))
847         ;; Allow the backend to save the article.
848         (save-excursion
849           (save-restriction
850             (narrow-to-region start (point))
851             (goto-char (point-min))
852             (nnmail-check-duplication message-id func artnum-func)
853             (setq end (point-max))))
854         (goto-char end)))))
855
856 (defun nnmail-process-mmdf-mail-format (func artnum-func)
857   (let ((delim "^\^A\^A\^A\^A$")
858         (case-fold-search t)
859         start message-id end)
860     (goto-char (point-min))
861     (if (not (and (re-search-forward delim nil t)
862                   (forward-line 1)))
863         ;; Possibly wrong format?
864         (error "Error, unknown mail format! (Possibly corrupted.)")
865       ;; Carry on until the bitter end.
866       (while (not (eobp))
867         (setq start (point))
868         ;; Find the end of the head.
869         (narrow-to-region
870          start 
871          (if (search-forward "\n\n" nil t)
872              (1- (point))
873            ;; This will never happen, but just to be on the safe side --
874            ;; if there is no head-body delimiter, we search a bit manually.
875            (while (and (looking-at "From \\|[^ \t]+:")
876                        (not (eobp)))
877              (forward-line 1)
878              (point))))
879         ;; Find the Message-ID header.
880         (goto-char (point-min))
881         (if (re-search-forward "^Message-ID:[ \t]*\\(<[^>]+>\\)" nil t)
882             (setq message-id (match-string 1))
883           ;; There is no Message-ID here, so we create one.
884           (save-excursion
885             (when (re-search-backward "^Message-ID:" nil t)
886               (beginning-of-line)
887               (insert "Original-")))
888           (forward-line 1)
889           (insert "Message-ID: " (setq message-id (nnmail-message-id)) "\n"))
890         (run-hooks 'nnmail-prepare-incoming-header-hook)
891         ;; Find the end of this article.
892         (goto-char (point-max))
893         (widen)
894         (if (re-search-forward delim nil t)
895             (beginning-of-line)
896           (goto-char (point-max)))
897         ;; Allow the backend to save the article.
898         (save-excursion
899           (save-restriction
900             (narrow-to-region start (point))
901             (goto-char (point-min))
902             (nnmail-check-duplication message-id func artnum-func)
903             (setq end (point-max))))
904         (goto-char end)
905         (forward-line 2)))))
906
907 (defun nnmail-split-incoming (incoming func &optional exit-func
908                                        group artnum-func)
909   "Go through the entire INCOMING file and pick out each individual mail.
910 FUNC will be called with the buffer narrowed to each mail."
911   (let (;; If this is a group-specific split, we bind the split
912         ;; methods to just this group.
913         (nnmail-split-methods (if (and group
914                                        (or (eq nnmail-spool-file 'procmail)
915                                            nnmail-use-procmail)
916                                        (not nnmail-resplit-incoming))
917                                   (list (list group ""))
918                                 nnmail-split-methods)))
919     (save-excursion
920       ;; Insert the incoming file.
921       (set-buffer (get-buffer-create " *nnmail incoming*"))
922       (buffer-disable-undo (current-buffer))
923       (erase-buffer)
924       (nnheader-insert-file-contents incoming)
925       (unless (zerop (buffer-size))
926         (goto-char (point-min))
927         (save-excursion (run-hooks 'nnmail-prepare-incoming-hook))
928         ;; Handle both babyl, MMDF and unix mail formats, since movemail will
929         ;; use the former when fetching from a mailbox, the latter when
930         ;; fetches from a file.
931         (cond ((or (looking-at "\^L")
932                    (looking-at "BABYL OPTIONS:"))
933                (nnmail-process-babyl-mail-format func artnum-func))
934               ((looking-at "\^A\^A\^A\^A")
935                (nnmail-process-mmdf-mail-format func artnum-func))
936               (t
937                (nnmail-process-unix-mail-format func artnum-func))))
938       (when exit-func
939         (funcall exit-func))
940       (kill-buffer (current-buffer)))))
941
942 ;; Mail crossposts suggested by Brian Edmonds <edmonds@cs.ubc.ca>. 
943 (defun nnmail-article-group (func)
944   "Look at the headers and return an alist of groups that match.
945 FUNC will be called with the group name to determine the article number."
946   (let ((methods nnmail-split-methods)
947         (obuf (current-buffer))
948         (beg (point-min))
949         end group-art method)
950     (if (and (sequencep methods) (= (length methods) 1))
951         ;; If there is only just one group to put everything in, we
952         ;; just return a list with just this one method in.
953         (setq group-art
954               (list (cons (caar methods) (funcall func (caar methods)))))
955       ;; We do actual comparison.
956       (save-excursion
957         ;; Find headers.
958         (goto-char beg)
959         (setq end (if (search-forward "\n\n" nil t) (point) (point-max)))
960         (set-buffer nntp-server-buffer)
961         (erase-buffer)
962         ;; Copy the headers into the work buffer.
963         (insert-buffer-substring obuf beg end)
964         ;; Fold continuation lines.
965         (goto-char (point-min))
966         (while (re-search-forward "\\(\r?\n[ \t]+\\)+" nil t)
967           (replace-match " " t t))
968         ;; Allow washing.
969         (run-hooks 'nnmail-split-hook)
970         (if (and (symbolp nnmail-split-methods)
971                  (fboundp nnmail-split-methods))
972             (let ((split
973                    (condition-case nil
974                        (or (funcall nnmail-split-methods)
975                            '("bogus"))
976                      (error
977                       (message 
978                        "Error in `nnmail-split-methods'; using `bogus' mail group")
979                       (sit-for 1)
980                       '("bogus")))))
981               (unless (equal split '(junk))
982                 ;; `nnmail-split-methods' is a function, so we just call 
983                 ;; this function here and use the result.
984                 (setq group-art
985                       (mapcar
986                        (lambda (group) (cons group (funcall func group)))
987                        split))))
988           ;; Go through the split methods to find a match.
989           (while (and methods (or nnmail-crosspost (not group-art)))
990             (goto-char (point-max))
991             (setq method (pop methods))
992             (if (or methods
993                     (not (equal "" (nth 1 method))))
994                 (when (and
995                        (ignore-errors
996                          (if (stringp (nth 1 method))
997                              (re-search-backward (cadr method) nil t)
998                            ;; Function to say whether this is a match.
999                            (funcall (nth 1 method) (car method))))
1000                        ;; Don't enter the article into the same 
1001                        ;; group twice.
1002                        (not (assoc (car method) group-art)))
1003                   (push (cons (car method) (funcall func (car method)))
1004                         group-art))
1005               ;; This is the final group, which is used as a 
1006               ;; catch-all.
1007               (unless group-art
1008                 (setq group-art 
1009                       (list (cons (car method)
1010                                   (funcall func (car method)))))))))
1011         ;; See whether the split methods returned `junk'.
1012         (if (equal group-art '(junk))
1013             nil
1014           (nreverse (delq 'junk group-art)))))))
1015
1016 (defun nnmail-insert-lines ()
1017   "Insert how many lines there are in the body of the mail.
1018 Return the number of characters in the body."
1019   (let (lines chars)
1020     (save-excursion
1021       (goto-char (point-min))
1022       (when (search-forward "\n\n" nil t)
1023         (setq chars (- (point-max) (point)))
1024         (setq lines (count-lines (point) (point-max)))
1025         (forward-char -1)
1026         (save-excursion
1027           (when (re-search-backward "^Lines: " nil t)
1028             (delete-region (point) (progn (forward-line 1) (point)))))
1029         (beginning-of-line)
1030         (insert (format "Lines: %d\n" (max lines 0)))
1031         chars))))
1032
1033 (defun nnmail-insert-xref (group-alist)
1034   "Insert an Xref line based on the (group . article) alist."
1035   (save-excursion
1036     (goto-char (point-min))
1037     (when (search-forward "\n\n" nil t)
1038       (forward-char -1)
1039       (when (re-search-backward "^Xref: " nil t)
1040         (delete-region (match-beginning 0)
1041                        (progn (forward-line 1) (point))))
1042       (insert (format "Xref: %s" (system-name)))
1043       (while group-alist
1044         (insert (format " %s:%d" (caar group-alist) (cdar group-alist)))
1045         (setq group-alist (cdr group-alist)))
1046       (insert "\n"))))
1047
1048 ;;; Message washing functions
1049
1050 (defun nnmail-remove-leading-whitespace ()
1051   "Remove excessive whitespace from all headers."
1052   (goto-char (point-min))
1053   (while (re-search-forward "^\\([^ :]+: \\) +" nil t)
1054     (replace-match "\\1" t)))
1055
1056 (defun nnmail-remove-list-identifiers ()
1057   "Remove list identifiers from Subject headers."
1058   (let ((regexp (if (stringp nnmail-list-identifiers) nnmail-list-identifiers
1059                   (mapconcat 'identity nnmail-list-identifiers "\\|"))))
1060     (when regexp
1061       (goto-char (point-min))
1062       (when (re-search-forward
1063              (concat "^Subject: +\\(Re: +\\)?\\(" regexp "\\) *")
1064              nil t)
1065         (delete-region (match-beginning 2) (match-end 0))))))
1066
1067 (defun nnmail-remove-tabs ()
1068   "Translate TAB characters into SPACE characters."
1069   (subst-char-in-region (point-min) (point-max) ?\t ?  t))
1070
1071 ;;; Utility functions
1072
1073 ;; Written by byer@mv.us.adobe.com (Scott Byer).
1074 (defun nnmail-make-complex-temp-name (prefix)
1075   (let ((newname (make-temp-name prefix))
1076         (newprefix prefix))
1077     (while (file-exists-p newname)
1078       (setq newprefix (concat newprefix "x"))
1079       (setq newname (make-temp-name newprefix)))
1080     newname))
1081
1082 ;; Written by Per Abrahamsen <amanda@iesd.auc.dk>.
1083
1084 (defun nnmail-split-fancy ()
1085   "Fancy splitting method.
1086 See the documentation for the variable `nnmail-split-fancy' for documentation."
1087   (let ((syntab (syntax-table)))
1088     (unwind-protect
1089         (progn
1090           (set-syntax-table nnmail-split-fancy-syntax-table)
1091           (nnmail-split-it nnmail-split-fancy))
1092       (set-syntax-table syntab))))
1093
1094 (defvar nnmail-split-cache nil)
1095 ;; Alist of split expressions their equivalent regexps.
1096
1097 (defun nnmail-split-it (split)
1098   ;; Return a list of groups matching SPLIT.
1099   (cond
1100    ;; nil split
1101    ((null split)
1102     nil)
1103
1104    ;; A group name.  Do the \& and \N subs into the string.
1105    ((stringp split)
1106     (list (nnmail-expand-newtext split)))
1107
1108    ;; Junk the message.
1109    ((eq split 'junk)
1110     (list 'junk))
1111
1112    ;; Builtin & operation.
1113    ((eq (car split) '&)
1114     (apply 'nconc (mapcar 'nnmail-split-it (cdr split))))
1115
1116    ;; Builtin | operation.
1117    ((eq (car split) '|)
1118     (let (done)
1119       (while (and (not done) (cdr split))
1120         (setq split (cdr split)
1121               done (nnmail-split-it (car split))))
1122       done))
1123
1124    ;; Builtin : operation.
1125    ((eq (car split) ':)
1126     (nnmail-split-it (eval (cdr split))))
1127
1128    ;; Check the cache for the regexp for this split.
1129    ;; FIX FIX FIX could avoid calling assq twice here
1130    ((assq split nnmail-split-cache)
1131     (goto-char (point-max))
1132     ;; FIX FIX FIX problem with re-search-backward is that if you have
1133     ;; a split: (from "foo-\\(bar\\|baz\\)@gnus.org "mail.foo.\\1")
1134     ;; and someone mails a message with 'To: foo-bar@gnus.org' and
1135     ;; 'CC: foo-baz@gnus.org', we'll pick 'mail.foo.baz' as the group
1136     ;; if the cc line is a later header, even though the other choice
1137     ;; is probably better.  Also, this routine won't do a crosspost
1138     ;; when there are two different matches.
1139     ;; I guess you could just make this more determined, and it could
1140     ;; look for still more matches prior to this one, and recurse
1141     ;; on each of the multiple matches hit.  Of course, then you'd
1142     ;; want to make sure that nnmail-article-group or nnmail-split-fancy
1143     ;; removed duplicates, since there might be more of those.
1144     ;; I guess we could also remove duplicates in the & split case, since
1145     ;; that's the only thing that can introduce them.
1146     (when (re-search-backward (cdr (assq split nnmail-split-cache)) nil t)
1147       ;; Someone might want to do a \N sub on this match, so get the
1148       ;; correct match positions.
1149       (goto-char (match-end 0))
1150       (let ((value (nth 1 split)))
1151         (re-search-backward (if (symbolp value)
1152                                 (cdr (assq value nnmail-split-abbrev-alist))
1153                               value)
1154                             (match-end 1)))
1155       (nnmail-split-it (nth 2 split))))
1156
1157    ;; Not in cache, compute a regexp for the field/value pair.
1158    (t
1159     (let* ((field (nth 0 split))
1160            (value (nth 1 split))
1161            (regexp (concat "^\\(\\("
1162                            (if (symbolp field)
1163                                (cdr (assq field nnmail-split-abbrev-alist))
1164                              field)
1165                            "\\):.*\\)\\<\\("
1166                            (if (symbolp value)
1167                                (cdr (assq value nnmail-split-abbrev-alist))
1168                              value)
1169                            "\\)\\>")))
1170       (push (cons split regexp) nnmail-split-cache)
1171       ;; Now that it's in the cache, just call nnmail-split-it again
1172       ;; on the same split, which will find it immediately in the cache.
1173       (nnmail-split-it split)))))
1174
1175 (defun nnmail-expand-newtext (newtext)
1176   (let ((len (length newtext))
1177         (pos 0)
1178         c expanded beg N did-expand)
1179     (while (< pos len)
1180       (setq beg pos)
1181       (while (and (< pos len)
1182                   (not (= (aref newtext pos) ?\\)))
1183         (setq pos (1+ pos)))
1184       (unless (= beg pos)
1185         (push (substring newtext beg pos) expanded))
1186       (when (< pos len)
1187         ;; we hit a \, expand it.
1188         (setq did-expand t)
1189         (setq pos (1+ pos))
1190         (setq c (aref newtext pos))
1191         (if (not (or (= c ?\&)
1192                      (and (>= c ?1)
1193                           (<= c ?9))))
1194             ;; \ followed by some character we don't expand
1195             (push (char-to-string c) expanded)
1196           ;; \& or \N
1197           (if (= c ?\&)
1198               (setq N 0)
1199             (setq N (- c ?0)))
1200           (when (match-beginning N)
1201             (push (buffer-substring (match-beginning N) (match-end N))
1202                   expanded))))
1203       (setq pos (1+ pos)))
1204     (if did-expand
1205         (apply 'concat (nreverse expanded))
1206       newtext)))
1207
1208 ;; Get a list of spool files to read.
1209 (defun nnmail-get-spool-files (&optional group)
1210   (if (null nnmail-spool-file)
1211       ;; No spool file whatsoever.
1212       nil
1213     (let* ((procmails 
1214             ;; If procmail is used to get incoming mail, the files
1215             ;; are stored in this directory.
1216             (and (file-exists-p nnmail-procmail-directory)
1217                  (or (eq nnmail-spool-file 'procmail)
1218                      nnmail-use-procmail)
1219                  (directory-files 
1220                   nnmail-procmail-directory 
1221                   t (concat (if group (concat "^" group) "")
1222                             nnmail-procmail-suffix "$"))))
1223            (p procmails)
1224            (crash (when (and (file-exists-p nnmail-crash-box)
1225                              (> (nnheader-file-size
1226                                  (file-truename nnmail-crash-box))
1227                                 0))
1228                     (list nnmail-crash-box))))
1229       ;; Remove any directories that inadvertently match the procmail
1230       ;; suffix, which might happen if the suffix is "". 
1231       (while p
1232         (when (file-directory-p (car p))
1233           (setq procmails (delete (car p) procmails)))
1234         (setq p (cdr p)))
1235       ;; Return the list of spools.
1236       (append 
1237        crash
1238        (cond ((and group
1239                    (or (eq nnmail-spool-file 'procmail)
1240                        nnmail-use-procmail)
1241                    procmails)
1242               procmails)
1243              ((and group
1244                    (eq nnmail-spool-file 'procmail))
1245               nil)
1246              ((listp nnmail-spool-file)
1247               (nconc
1248                (apply 
1249                 'nconc
1250                 (mapcar 
1251                  (lambda (file)
1252                    (if (file-directory-p file)
1253                        (nnheader-directory-regular-files file)
1254                      (list file)))
1255                  nnmail-spool-file))
1256                procmails))
1257              ((and (stringp nnmail-spool-file)
1258                    (not (file-directory-p nnmail-spool-file)))
1259               (cons nnmail-spool-file procmails))
1260              ((and (stringp nnmail-spool-file)
1261                    (file-directory-p nnmail-spool-file))
1262               (nconc
1263                (nnheader-directory-regular-files nnmail-spool-file)
1264                procmails))
1265              ((eq nnmail-spool-file 'pop)
1266               (cons (format "po:%s" (user-login-name)) procmails))
1267              (t
1268               procmails))))))
1269
1270 ;; Activate a backend only if it isn't already activated. 
1271 ;; If FORCE, re-read the active file even if the backend is 
1272 ;; already activated.
1273 (defun nnmail-activate (backend &optional force)
1274   (let (file timestamp file-time)
1275     (if (or (not (symbol-value (intern (format "%s-group-alist" backend))))
1276             force
1277             (and (setq file (ignore-errors
1278                               (symbol-value (intern (format "%s-active-file" 
1279                                                             backend)))))
1280                  (setq file-time (nth 5 (file-attributes file)))
1281                  (or (not
1282                       (setq timestamp
1283                             (condition-case ()
1284                                 (symbol-value (intern
1285                                                (format "%s-active-timestamp" 
1286                                                        backend)))
1287                               (error 'none))))
1288                      (not (consp timestamp))
1289                      (equal timestamp '(0 0))
1290                      (> (nth 0 file-time) (nth 0 timestamp))
1291                      (and (= (nth 0 file-time) (nth 0 timestamp))
1292                           (> (nth 1 file-time) (nth 1 timestamp))))))
1293         (save-excursion
1294           (or (eq timestamp 'none)
1295               (set (intern (format "%s-active-timestamp" backend)) 
1296 ;;; dmoore@ucsd.edu 25.10.96
1297 ;;; it's not always the case that current-time
1298 ;;; does correspond to changes in the file's time.  So just compare
1299 ;;; the file's new time against its own previous time.
1300 ;;;                (current-time)
1301                    file-time
1302                    ))
1303           (funcall (intern (format "%s-request-list" backend)))
1304 ;;; dmoore@ucsd.edu 25.10.96
1305 ;;; BACKEND-request-list already does this itself!
1306 ;;;       (set (intern (format "%s-group-alist" backend)) 
1307 ;;;            (nnmail-get-active))
1308           ))
1309     t))
1310
1311 (defun nnmail-message-id ()
1312   (concat "<" (message-unique-id) "@totally-fudged-out-message-id>"))
1313
1314 ;;;
1315 ;;; nnmail duplicate handling
1316 ;;;
1317
1318 (defvar nnmail-cache-buffer nil)
1319
1320 (defun nnmail-cache-open ()
1321   (if (or (not nnmail-treat-duplicates)
1322           (and nnmail-cache-buffer
1323                (buffer-name nnmail-cache-buffer)))
1324       ()                                ; The buffer is open.
1325     (save-excursion
1326       (set-buffer 
1327        (setq nnmail-cache-buffer 
1328              (get-buffer-create " *nnmail message-id cache*")))
1329       (buffer-disable-undo (current-buffer))
1330       (when (file-exists-p nnmail-message-id-cache-file)
1331         (nnheader-insert-file-contents nnmail-message-id-cache-file))
1332       (set-buffer-modified-p nil)
1333       (current-buffer))))
1334
1335 (defun nnmail-cache-close ()
1336   (when (and nnmail-cache-buffer
1337              nnmail-treat-duplicates
1338              (buffer-name nnmail-cache-buffer)
1339              (buffer-modified-p nnmail-cache-buffer))
1340     (save-excursion
1341       (set-buffer nnmail-cache-buffer)
1342       ;; Weed out the excess number of Message-IDs.
1343       (goto-char (point-max))
1344       (when (search-backward "\n" nil t nnmail-message-id-cache-length)
1345         (progn
1346           (beginning-of-line)
1347           (delete-region (point-min) (point))))
1348       ;; Save the buffer.
1349       (or (file-exists-p (file-name-directory nnmail-message-id-cache-file))
1350           (make-directory (file-name-directory nnmail-message-id-cache-file)
1351                           t))
1352       (nnmail-write-region (point-min) (point-max)
1353                            nnmail-message-id-cache-file nil 'silent)
1354       (set-buffer-modified-p nil)
1355       (setq nnmail-cache-buffer nil)
1356       ;;(kill-buffer (current-buffer))
1357       )))
1358
1359 (defun nnmail-cache-insert (id)
1360   (when nnmail-treat-duplicates
1361     (save-excursion
1362       (set-buffer nnmail-cache-buffer)
1363       (goto-char (point-max))
1364       (insert id "\n"))))
1365
1366 (defun nnmail-cache-id-exists-p (id)
1367   (when nnmail-treat-duplicates
1368     (save-excursion
1369       (set-buffer nnmail-cache-buffer)
1370       (goto-char (point-max))
1371       (search-backward id nil t))))
1372
1373 (defun nnmail-check-duplication (message-id func artnum-func)
1374   (run-hooks 'nnmail-prepare-incoming-message-hook)
1375   ;; If this is a duplicate message, then we do not save it.
1376   (let* ((duplication (nnmail-cache-id-exists-p message-id))
1377          (case-fold-search t)
1378          (action (when duplication
1379                    (cond
1380                     ((memq nnmail-treat-duplicates '(warn delete))
1381                      nnmail-treat-duplicates)
1382                     ((nnheader-functionp nnmail-treat-duplicates)
1383                      (funcall nnmail-treat-duplicates message-id))
1384                     (t
1385                      nnmail-treat-duplicates))))
1386          group-art)
1387     ;; Let the backend save the article (or not).
1388     (cond
1389      ((not duplication)
1390       (nnmail-cache-insert message-id)
1391       (funcall func (setq group-art
1392                           (nreverse (nnmail-article-group artnum-func)))))
1393      ((eq action 'delete)
1394       (setq group-art nil))
1395      ((eq action 'warn)
1396       ;; We insert a warning.
1397       (let ((case-fold-search t)
1398             (newid (nnmail-message-id)))
1399         (goto-char (point-min))
1400         (when (re-search-forward "^message-id:" nil t)
1401           (beginning-of-line)
1402           (insert "Original-"))
1403         (beginning-of-line)
1404         (insert 
1405          "Message-ID: " newid "\n"
1406          "Gnus-Warning: This is a duplicate of message " message-id "\n")
1407         (nnmail-cache-insert newid)
1408         (funcall func (setq group-art
1409                             (nreverse (nnmail-article-group artnum-func))))))
1410      (t
1411       (funcall func (setq group-art
1412                           (nreverse (nnmail-article-group artnum-func))))))
1413     ;; Add the group-art list to the history list.
1414     (if group-art
1415         (push group-art nnmail-split-history)
1416       (delete-region (point-min) (point-max)))))
1417
1418 ;;; Get new mail.
1419
1420 (defun nnmail-get-value (&rest args)
1421   (let ((sym (intern (apply 'format args))))
1422     (when (boundp sym)
1423       (symbol-value sym))))
1424
1425 (defun nnmail-get-new-mail (method exit-func temp
1426                                    &optional group spool-func)
1427   "Read new incoming mail."
1428   ;; Nix out the previous split history.
1429   (unless group
1430     (setq nnmail-split-history nil))
1431   (let* ((spools (nnmail-get-spool-files group))
1432          (group-in group)
1433          incoming incomings spool)
1434     (when (and (nnmail-get-value "%s-get-new-mail" method)
1435                nnmail-spool-file)
1436       ;; We first activate all the groups.
1437       (nnmail-activate method)
1438       ;; Allow the user to hook.
1439       (run-hooks 'nnmail-pre-get-new-mail-hook)
1440       ;; Open the message-id cache.
1441       (nnmail-cache-open)
1442       ;; The we go through all the existing spool files and split the
1443       ;; mail from each.
1444       (while spools
1445         (setq spool (pop spools))
1446         ;; We read each spool file if either the spool is a POP-mail
1447         ;; spool, or the file exists.  We can't check for the
1448         ;; existence of POPped mail.
1449         (when (or (string-match "^po:" spool)
1450                   (and (file-exists-p (file-truename spool))
1451                        (> (nnheader-file-size (file-truename spool)) 0)))
1452           (nnheader-message 3 "%s: Reading incoming mail..." method)
1453           (when (and (nnmail-move-inbox spool)
1454                      (file-exists-p nnmail-crash-box))
1455             ;; There is new mail.  We first find out if all this mail
1456             ;; is supposed to go to some specific group.
1457             (setq group (nnmail-get-split-group spool group-in))
1458             ;; We split the mail
1459             (nnmail-split-incoming 
1460              nnmail-crash-box (intern (format "%s-save-mail" method))
1461              spool-func group (intern (format "%s-active-number" method)))
1462             ;; Check whether the inbox is to be moved to the special tmp dir. 
1463             (setq incoming
1464                   (nnmail-make-complex-temp-name 
1465                    (expand-file-name 
1466                     (if nnmail-tmp-directory
1467                         (concat 
1468                          (file-name-as-directory nnmail-tmp-directory)
1469                          (file-name-nondirectory (concat temp "Incoming")))
1470                       (concat temp "Incoming")))))
1471             (rename-file nnmail-crash-box incoming t)
1472             (push incoming incomings))))
1473       ;; If we did indeed read any incoming spools, we save all info. 
1474       (when incomings
1475         (nnmail-save-active 
1476          (nnmail-get-value "%s-group-alist" method)
1477          (nnmail-get-value "%s-active-file" method))
1478         (when exit-func
1479           (funcall exit-func))
1480         (run-hooks 'nnmail-read-incoming-hook)
1481         (nnheader-message 3 "%s: Reading incoming mail...done" method))
1482       ;; Close the message-id cache.
1483       (nnmail-cache-close)
1484       ;; Allow the user to hook.
1485       (run-hooks 'nnmail-post-get-new-mail-hook)
1486       ;; Delete all the temporary files.
1487       (while incomings
1488         (setq incoming (pop incomings))
1489         (and nnmail-delete-incoming
1490              (file-exists-p incoming)
1491              (file-writable-p incoming)
1492              (delete-file incoming))))))
1493
1494 (defun nnmail-expired-article-p (group time force &optional inhibit)
1495   "Say whether an article that is TIME old in GROUP should be expired."
1496   (if force
1497       t
1498     (let ((days (or (and nnmail-expiry-wait-function
1499                          (funcall nnmail-expiry-wait-function group))
1500                     nnmail-expiry-wait)))
1501       (cond ((or (eq days 'never)
1502                  (and (not force)
1503                       inhibit))
1504              ;; This isn't an expirable group.
1505              nil)
1506             ((eq days 'immediate)
1507              ;; We expire all articles on sight.
1508              t)
1509             ((equal time '(0 0))
1510              ;; This is an ange-ftp group, and we don't have any dates.
1511              nil)
1512             ((numberp days)
1513              (setq days (nnmail-days-to-time days))
1514              ;; Compare the time with the current time.
1515              (nnmail-time-less days (nnmail-time-since time)))))))
1516
1517 (defvar nnmail-read-passwd nil)
1518 (defun nnmail-read-passwd (prompt &rest args)
1519   "Read a password using PROMPT.
1520 If ARGS, PROMPT is used as an argument to `format'."
1521   (let ((prompt
1522          (if args
1523              (apply 'format prompt args)
1524            prompt)))
1525     (unless nnmail-read-passwd
1526       (if (load "passwd" t)
1527           (setq nnmail-read-passwd 'read-passwd)
1528         (autoload 'ange-ftp-read-passwd "ange-ftp")
1529         (setq nnmail-read-passwd 'ange-ftp-read-passwd)))
1530     (funcall nnmail-read-passwd prompt)))
1531
1532 (defun nnmail-check-syntax ()
1533   "Check (and modify) the syntax of the message in the current buffer."
1534   (save-restriction
1535     (message-narrow-to-head)
1536     (let ((case-fold-search t))
1537       (unless (re-search-forward "^Message-ID:" nil t)
1538         (insert "Message-ID: " (nnmail-message-id) "\n")))))
1539
1540 (defun nnmail-write-region (start end filename &optional append visit lockname)
1541   "Do a `write-region', and then set the file modes."
1542   (write-region start end filename append visit lockname)
1543   (set-file-modes filename nnmail-default-file-modes))
1544
1545 ;;;
1546 ;;; Status functions
1547 ;;;
1548
1549 (defun nnmail-replace-status (name value)
1550   "Make status NAME and VALUE part of the current status line."
1551   (save-restriction
1552     (message-narrow-to-head)
1553     (let ((status (nnmail-decode-status)))
1554       (setq status (delq (member name status) status))
1555       (when value
1556         (push (cons name value) status))
1557       (message-remove-header "status")
1558       (goto-char (point-max))
1559       (insert "Status: " (nnmail-encode-status status) "\n"))))
1560
1561 (defun nnmail-decode-status ()
1562   "Return a status-value alist from STATUS."
1563   (goto-char (point-min))
1564   (when (re-search-forward "^Status: " nil t)
1565     (let (name value status)
1566       (save-restriction
1567         ;; Narrow to the status.
1568         (narrow-to-region
1569          (point)
1570          (if (re-search-forward "^[^ \t]" nil t)
1571              (1- (point))
1572            (point-max)))
1573         ;; Go through all elements and add them to the list.
1574         (goto-char (point-min))
1575         (while (re-search-forward "[^ \t=]+" nil t)
1576           (setq name (match-string 0))
1577           (if (not (= (following-char) ?=))
1578               ;; Implied "yes".
1579               (setq value "yes")
1580             (forward-char 1)
1581             (if (not (= (following-char) ?\"))
1582                 (if (not (looking-at "[^ \t]"))
1583                     ;; Implied "no".
1584                     (setq value "no")
1585                   ;; Unquoted value.
1586                   (setq value (match-string 0))
1587                   (goto-char (match-end 0)))
1588               ;; Quoted value.
1589               (setq value (read (current-buffer)))))
1590           (push (cons name value) status)))
1591       status)))
1592
1593 (defun nnmail-encode-status (status)
1594   "Return a status string from STATUS."
1595   (mapconcat
1596    (lambda (elem)
1597      (concat
1598       (car elem) "="
1599       (if (string-match "[ \t]" (cdr elem))
1600           (prin1-to-string (cdr elem))
1601         (cdr elem))))
1602    status " "))
1603
1604 (defun nnmail-split-history ()
1605   "Generate an overview of where the last mail split put articles."
1606   (interactive)
1607   (unless nnmail-split-history
1608     (error "No current split history"))
1609   (with-output-to-temp-buffer "*nnmail split history*"
1610     (let ((history nnmail-split-history)
1611           elem)
1612       (while (setq elem (pop history))
1613         (princ (mapconcat (lambda (ga)
1614                             (concat (car ga) ":" (int-to-string (cdr ga))))
1615                           elem
1616                           ", "))
1617         (princ "\n")))))
1618
1619 (defun nnmail-new-mail-p (group)
1620   "Say whether GROUP has new mail."
1621   (let ((his nnmail-split-history)
1622         found)
1623     (while his
1624       (when (assoc group (pop his))
1625         (setq found t
1626               his nil)))
1627     found))
1628         
1629 (run-hooks 'nnmail-load-hook)
1630             
1631 (provide 'nnmail)
1632
1633 ;;; nnmail.el ends here