*** 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 t
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                         (number-to-string
454                          (* 60 (timezone-zone-to-minute (aref d1 4))))))))
455     ;; If we get an error, then we just return a 0 time.
456     (error (list 0 0))))
457
458 (defun nnmail-time-less (t1 t2)
459   "Say whether time T1 is less than time T2."
460   (or (< (car t1) (car t2))
461       (and (= (car t1) (car t2))
462            (< (nth 1 t1) (nth 1 t2)))))
463
464 (defun nnmail-days-to-time (days)
465   "Convert DAYS into time."
466   (let* ((seconds (* 1.0 days 60 60 24))
467          (rest (expt 2 16))
468          (ms (condition-case nil (round (/ seconds rest))
469                (range-error (expt 2 16)))))
470     (list ms (condition-case nil (round (- seconds (* ms rest)))
471                (range-error (expt 2 16))))))
472
473 (defun nnmail-time-since (time)
474   "Return the time since TIME, which is either an internal time or a date."
475   (when (stringp time)
476     ;; Convert date strings to internal time.
477     (setq time (nnmail-date-to-time time)))
478   (let* ((current (current-time))
479          (rest (when (< (nth 1 current) (nth 1 time))
480                  (expt 2 16))))
481     (list (- (+ (car current) (if rest -1 0)) (car time))
482           (- (+ (or rest 0) (nth 1 current)) (nth 1 time)))))
483
484 ;; Function rewritten from rmail.el.
485 (defun nnmail-move-inbox (inbox)
486   "Move INBOX to `nnmail-crash-box'."
487   (if (not (file-writable-p nnmail-crash-box))
488       (gnus-error 1 "Can't write to crash box %s.  Not moving mail."
489                   nnmail-crash-box)
490     ;; If the crash box exists and is empty, we delete it.
491     (when (and (file-exists-p nnmail-crash-box)
492                (zerop (nnheader-file-size (file-truename nnmail-crash-box))))
493       (delete-file nnmail-crash-box))
494     (let ((inbox (file-truename (expand-file-name inbox)))
495           (tofile (file-truename (expand-file-name nnmail-crash-box)))
496           movemail popmail errors)
497       (if (setq popmail (string-match
498                          "^po:" (file-name-nondirectory inbox)))
499           (setq inbox (file-name-nondirectory inbox))
500         (setq movemail t)
501         ;; On some systems, /usr/spool/mail/foo is a directory
502         ;; and the actual inbox is /usr/spool/mail/foo/foo.
503         (when (file-directory-p inbox)
504           (setq inbox (expand-file-name (user-login-name) inbox))))
505       (if (member inbox nnmail-moved-inboxes)
506           ;; We don't try to move an already moved inbox.
507           nil
508         (if popmail
509             (progn
510               (when (and nnmail-pop-password
511                          (not nnmail-internal-password))
512                 (setq nnmail-internal-password nnmail-pop-password))
513               (when (and nnmail-pop-password-required
514                          (not nnmail-internal-password))
515                 (setq nnmail-internal-password
516                       (nnmail-read-passwd
517                        (format "Password for %s: "
518                                (substring inbox (+ popmail 3))))))
519               (message "Getting mail from post office ..."))
520           (when (or (and (file-exists-p tofile)
521                          (/= 0 (nnheader-file-size tofile)))
522                     (and (file-exists-p inbox)
523                          (/= 0 (nnheader-file-size inbox))))
524             (message "Getting mail from %s..." inbox)))
525         ;; Set TOFILE if have not already done so, and
526         ;; rename or copy the file INBOX to TOFILE if and as appropriate.
527         (cond 
528          ((file-exists-p tofile)
529           ;; The crash box exists already.
530           t)
531          ((and (not popmail)
532                (not (file-exists-p inbox)))
533           ;; There is no inbox.
534           (setq tofile nil))
535          (t
536           ;; If getting from mail spool directory, use movemail to move
537           ;; rather than just renaming, so as to interlock with the
538           ;; mailer.
539           (unwind-protect
540               (save-excursion
541                 (setq errors (generate-new-buffer " *nnmail loss*"))
542                 (buffer-disable-undo errors)
543                 (let ((default-directory "/"))
544                   (if (nnheader-functionp nnmail-movemail-program)
545                       (funcall nnmail-movemail-program inbox tofile)
546                     (apply 
547                      'call-process
548                      (append
549                       (list
550                        (expand-file-name 
551                         nnmail-movemail-program exec-directory)
552                        nil errors nil inbox tofile)
553                       (when nnmail-internal-password
554                         (list nnmail-internal-password))))))
555                 (if (not (buffer-modified-p errors))
556                     ;; No output => movemail won
557                     (progn
558                       (unless popmail
559                         (when (file-exists-p tofile)
560                           (set-file-modes tofile nnmail-default-file-modes)))
561                       (push inbox nnmail-moved-inboxes))
562                   (set-buffer errors)
563                   ;; There may be a warning about older revisions.  We
564                   ;; ignore those.
565                   (goto-char (point-min))
566                   (if (search-forward "older revision" nil t)
567                       (progn
568                         (unless popmail
569                           (when (file-exists-p tofile)
570                             (set-file-modes tofile nnmail-default-file-modes)))
571                         (push inbox nnmail-moved-inboxes))
572                     ;; Probably a real error.
573                     (subst-char-in-region (point-min) (point-max) ?\n ?\  )
574                     (goto-char (point-max))
575                     (skip-chars-backward " \t")
576                     (delete-region (point) (point-max))
577                     (goto-char (point-min))
578                     (when (looking-at "movemail: ")
579                       (delete-region (point-min) (match-end 0)))
580                     (unless (yes-or-no-p
581                              (format "movemail: %s.  Continue? "
582                                      (buffer-string)))
583                       (error "%s" (buffer-string)))
584                     (setq tofile nil)))))))
585         (message "Getting mail from %s...done" inbox)
586         (and errors
587              (buffer-name errors)
588              (kill-buffer errors))
589         tofile))))
590
591 (defun nnmail-get-active ()
592   "Returns an assoc of group names and active ranges.
593 nn*-request-list should have been called before calling this function."
594   (let (group-assoc)
595     ;; Go through all groups from the active list.
596     (save-excursion
597       (set-buffer nntp-server-buffer)
598       (goto-char (point-min))
599       (while (re-search-forward 
600               "^\\([^ \t]+\\)[ \t]+\\([0-9]+\\)[ \t]+\\([0-9]+\\)" nil t)
601         ;; We create an alist with `(GROUP (LOW . HIGH))' elements.
602         (push (list (match-string 1)
603                     (cons (string-to-int (match-string 3))
604                           (string-to-int (match-string 2))))
605               group-assoc)))
606     group-assoc))
607
608 (defun nnmail-save-active (group-assoc file-name)
609   "Save GROUP-ASSOC in ACTIVE-FILE."
610   (when file-name
611     (nnheader-temp-write file-name
612       (nnmail-generate-active group-assoc))))
613
614 (defun nnmail-generate-active (alist)
615   "Generate an active file from group-alist ALIST."
616   (erase-buffer)
617   (let (group)
618     (while (setq group (pop alist))
619       (insert (format "%s %d %d y\n" (car group) (cdadr group)
620                       (caadr group))))))
621
622 (defun nnmail-get-split-group (file group)
623   "Find out whether this FILE is to be split into GROUP only.
624 If GROUP is non-nil and we are using procmail, return the group name
625 only when the file is the correct procmail file.  When GROUP is nil,
626 return nil if FILE is a spool file or the procmail group for which it
627 is a spool.  If not using procmail, return GROUP."
628   (if (or (eq nnmail-spool-file 'procmail)
629           nnmail-use-procmail)
630       (if (string-match (concat "^" (expand-file-name
631                                      (file-name-as-directory
632                                       nnmail-procmail-directory))
633                                 "\\([^/]*\\)" nnmail-procmail-suffix "$")
634                         (expand-file-name file))
635           (let ((procmail-group (substring (expand-file-name file)
636                                            (match-beginning 1)
637                                            (match-end 1))))
638             (if group 
639                 (if (string-equal group procmail-group)
640                     group
641                   nil)
642               procmail-group))
643         nil)
644     group))
645
646 (defun nnmail-process-babyl-mail-format (func artnum-func)
647   (let ((case-fold-search t)
648         start message-id content-length do-search end)
649     (goto-char (point-min))
650     (while (not (eobp))
651       (re-search-forward
652        "\f\n0, *unseen,+\n\\(\\*\\*\\* EOOH \\*\\*\\*\n\\)?" nil t)
653       (goto-char (match-end 0))
654       (delete-region (match-beginning 0) (match-end 0))
655       (narrow-to-region
656        (setq start (point))
657        (progn
658          ;; Skip all the headers in case there are more "From "s...
659          (or (search-forward "\n\n" nil t)
660              (search-forward-regexp "^[^:]*\\( .*\\|\\)$" nil t)
661              (search-forward "\1f\f"))
662          (point)))
663       ;; Unquote the ">From " line, if any.
664       (goto-char (point-min))
665       (when (looking-at ">From ")
666         (replace-match "X-From-Line: ") )
667       (run-hooks 'nnmail-prepare-incoming-header-hook)
668       (goto-char (point-max))
669       ;; Find the Message-ID header.
670       (save-excursion
671         (if (re-search-backward "^Message-ID:[ \t]*\\(<[^>]*>\\)" nil t)
672             (setq message-id (buffer-substring (match-beginning 1)
673                                                (match-end 1)))
674           ;; There is no Message-ID here, so we create one.
675           (save-excursion
676             (when (re-search-backward "^Message-ID:" nil t)
677               (beginning-of-line)
678               (insert "Original-")))
679           (forward-line -1)
680           (insert "Message-ID: " (setq message-id (nnmail-message-id))
681                   "\n")))
682       ;; Look for a Content-Length header.
683       (if (not (save-excursion
684                  (and (re-search-backward 
685                        "^Content-Length:[ \t]*\\([0-9]+\\)" start t)
686                       (setq content-length (string-to-int
687                                             (buffer-substring 
688                                              (match-beginning 1)
689                                              (match-end 1))))
690                       ;; We destroy the header, since none of
691                       ;; the backends ever use it, and we do not
692                       ;; want to confuse other mailers by having
693                       ;; a (possibly) faulty header.
694                       (progn (insert "X-") t))))
695           (setq do-search t)
696         (widen)
697         (if (or (= (+ (point) content-length) (point-max))
698                 (save-excursion
699                   (goto-char (+ (point) content-length))
700                   (looking-at "\1f")))
701             (progn
702               (goto-char (+ (point) content-length))
703               (setq do-search nil))
704           (setq do-search t)))
705       (widen)
706       ;; Go to the beginning of the next article - or to the end
707       ;; of the buffer.  
708       (when do-search
709         (if (re-search-forward "^\1f" nil t)
710             (goto-char (match-beginning 0))
711           (goto-char (1- (point-max)))))
712       (delete-char 1)                   ; delete ^_
713       (save-excursion
714         (save-restriction
715           (narrow-to-region start (point))
716           (goto-char (point-min))
717           (nnmail-check-duplication message-id func artnum-func)
718           (setq end (point-max))))
719       (goto-char end))))
720
721 (defun nnmail-search-unix-mail-delim ()
722   "Put point at the beginning of the next Unix mbox message."
723   ;; Algorithm used to find the the next article in the
724   ;; brain-dead Unix mbox format:
725   ;;
726   ;; 1) Search for "^From ".
727   ;; 2) If we find it, then see whether the previous
728   ;;    line is blank and the next line looks like a header.
729   ;; Then it's possible that this is a mail delim, and we use it.
730   (let ((case-fold-search nil)
731         found)
732     (while (not found)
733       (if (not (re-search-forward "^From " nil t))
734           (setq found 'no)
735         (save-excursion
736           (beginning-of-line)
737           (when (and (or (bobp)
738                          (save-excursion
739                            (forward-line -1)
740                            (= (following-char) ?\n)))
741                      (save-excursion
742                        (forward-line 1)
743                        (while (looking-at ">From ")
744                          (forward-line 1))
745                        (looking-at "[^ \t:]+[ \t]*:")))
746             (setq found 'yes)))))
747     (beginning-of-line)
748     (eq found 'yes)))
749
750 (defun nnmail-search-unix-mail-delim-backward ()
751   "Put point at the beginning of the current Unix mbox message."
752   ;; Algorithm used to find the the next article in the
753   ;; brain-dead Unix mbox format:
754   ;;
755   ;; 1) Search for "^From ".
756   ;; 2) If we find it, then see whether the previous
757   ;;    line is blank and the next line looks like a header.
758   ;; Then it's possible that this is a mail delim, and we use it.
759   (let ((case-fold-search nil)
760         found)
761     (while (not found)
762       (if (not (re-search-backward "^From " nil t))
763           (setq found 'no)
764         (save-excursion
765           (beginning-of-line)
766           (when (and (or (bobp)
767                          (save-excursion
768                            (forward-line -1)
769                            (= (following-char) ?\n)))
770                      (save-excursion
771                        (forward-line 1)
772                        (while (looking-at ">From ")
773                          (forward-line 1))
774                        (looking-at "[^ \t:]+[ \t]*:")))
775             (setq found 'yes)))))
776     (beginning-of-line)
777     (eq found 'yes)))
778
779 (defun nnmail-process-unix-mail-format (func artnum-func)
780   (let ((case-fold-search t)
781         start message-id content-length end skip head-end)
782     (goto-char (point-min))
783     (if (not (and (re-search-forward "^From " nil t)
784                   (goto-char (match-beginning 0))))
785         ;; Possibly wrong format?
786         (error "Error, unknown mail format! (Possibly corrupted.)")
787       ;; Carry on until the bitter end.
788       (while (not (eobp))
789         (setq start (point)
790               end nil)
791         ;; Find the end of the head.
792         (narrow-to-region
793          start 
794          (if (search-forward "\n\n" nil t)
795              (1- (point))
796            ;; This will never happen, but just to be on the safe side --
797            ;; if there is no head-body delimiter, we search a bit manually.
798            (while (and (looking-at "From \\|[^ \t]+:")
799                        (not (eobp)))
800              (forward-line 1)
801              (point))))
802         ;; Find the Message-ID header.
803         (goto-char (point-min))
804         (if (re-search-forward "^Message-ID:[ \t]*\\(<[^>]+>\\)" nil t)
805             (setq message-id (match-string 1))
806           (save-excursion
807             (when (re-search-forward "^Message-ID:" nil t)
808               (beginning-of-line)
809               (insert "Original-")))
810           ;; There is no Message-ID here, so we create one.
811           (forward-line 1)
812           (insert "Message-ID: " (setq message-id (nnmail-message-id)) "\n"))
813         ;; Look for a Content-Length header.
814         (goto-char (point-min))
815         (if (not (re-search-forward
816                   "^Content-Length:[ \t]*\\([0-9]+\\)" nil t))
817             (setq content-length nil)
818           (setq content-length (string-to-int (match-string 1)))
819           ;; We destroy the header, since none of the backends ever 
820           ;; use it, and we do not want to confuse other mailers by
821           ;; having a (possibly) faulty header.
822           (beginning-of-line)
823           (insert "X-"))
824         (run-hooks 'nnmail-prepare-incoming-header-hook)
825         ;; Find the end of this article.
826         (goto-char (point-max))
827         (widen)
828         (setq head-end (point))
829         ;; We try the Content-Length value.  The idea: skip over the header
830         ;; separator, then check what happens content-length bytes into the
831         ;; message body.  This should be either the end ot the buffer, the
832         ;; message separator or a blank line followed by the separator.
833         ;; The blank line should probably be deleted.  If neither of the
834         ;; three is met, the content-length header is probably invalid.
835         (when content-length
836           (forward-line 1)
837           (setq skip (+ (point) content-length))
838           (goto-char skip)
839           (cond ((or (= skip (point-max))
840                      (= (1+ skip) (point-max)))
841                  (setq end (point-max)))
842                 ((looking-at "From ")
843                  (setq end skip))
844                 ((looking-at "[ \t]*\n\\(From \\)")
845                  (setq end (match-beginning 1)))
846                 (t (setq end nil))))
847         (if end
848             (goto-char end)
849           ;; No Content-Length, so we find the beginning of the next 
850           ;; article or the end of the buffer.
851           (goto-char head-end)
852           (or (nnmail-search-unix-mail-delim)
853               (goto-char (point-max))))
854         ;; Allow the backend to save the article.
855         (save-excursion
856           (save-restriction
857             (narrow-to-region start (point))
858             (goto-char (point-min))
859             (nnmail-check-duplication message-id func artnum-func)
860             (setq end (point-max))))
861         (goto-char end)))))
862
863 (defun nnmail-process-mmdf-mail-format (func artnum-func)
864   (let ((delim "^\^A\^A\^A\^A$")
865         (case-fold-search t)
866         start message-id end)
867     (goto-char (point-min))
868     (if (not (and (re-search-forward delim nil t)
869                   (forward-line 1)))
870         ;; Possibly wrong format?
871         (error "Error, unknown mail format! (Possibly corrupted.)")
872       ;; Carry on until the bitter end.
873       (while (not (eobp))
874         (setq start (point))
875         ;; Find the end of the head.
876         (narrow-to-region
877          start 
878          (if (search-forward "\n\n" nil t)
879              (1- (point))
880            ;; This will never happen, but just to be on the safe side --
881            ;; if there is no head-body delimiter, we search a bit manually.
882            (while (and (looking-at "From \\|[^ \t]+:")
883                        (not (eobp)))
884              (forward-line 1)
885              (point))))
886         ;; Find the Message-ID header.
887         (goto-char (point-min))
888         (if (re-search-forward "^Message-ID:[ \t]*\\(<[^>]+>\\)" nil t)
889             (setq message-id (match-string 1))
890           ;; There is no Message-ID here, so we create one.
891           (save-excursion
892             (when (re-search-backward "^Message-ID:" nil t)
893               (beginning-of-line)
894               (insert "Original-")))
895           (forward-line 1)
896           (insert "Message-ID: " (setq message-id (nnmail-message-id)) "\n"))
897         (run-hooks 'nnmail-prepare-incoming-header-hook)
898         ;; Find the end of this article.
899         (goto-char (point-max))
900         (widen)
901         (if (re-search-forward delim nil t)
902             (beginning-of-line)
903           (goto-char (point-max)))
904         ;; Allow the backend to save the article.
905         (save-excursion
906           (save-restriction
907             (narrow-to-region start (point))
908             (goto-char (point-min))
909             (nnmail-check-duplication message-id func artnum-func)
910             (setq end (point-max))))
911         (goto-char end)
912         (forward-line 2)))))
913
914 (defun nnmail-split-incoming (incoming func &optional exit-func
915                                        group artnum-func)
916   "Go through the entire INCOMING file and pick out each individual mail.
917 FUNC will be called with the buffer narrowed to each mail."
918   (let (;; If this is a group-specific split, we bind the split
919         ;; methods to just this group.
920         (nnmail-split-methods (if (and group
921                                        (or (eq nnmail-spool-file 'procmail)
922                                            nnmail-use-procmail)
923                                        (not nnmail-resplit-incoming))
924                                   (list (list group ""))
925                                 nnmail-split-methods)))
926     (save-excursion
927       ;; Insert the incoming file.
928       (set-buffer (get-buffer-create " *nnmail incoming*"))
929       (buffer-disable-undo (current-buffer))
930       (erase-buffer)
931       (nnheader-insert-file-contents incoming)
932       (unless (zerop (buffer-size))
933         (goto-char (point-min))
934         (save-excursion (run-hooks 'nnmail-prepare-incoming-hook))
935         ;; Handle both babyl, MMDF and unix mail formats, since movemail will
936         ;; use the former when fetching from a mailbox, the latter when
937         ;; fetches from a file.
938         (cond ((or (looking-at "\^L")
939                    (looking-at "BABYL OPTIONS:"))
940                (nnmail-process-babyl-mail-format func artnum-func))
941               ((looking-at "\^A\^A\^A\^A")
942                (nnmail-process-mmdf-mail-format func artnum-func))
943               (t
944                (nnmail-process-unix-mail-format func artnum-func))))
945       (when exit-func
946         (funcall exit-func))
947       (kill-buffer (current-buffer)))))
948
949 ;; Mail crossposts suggested by Brian Edmonds <edmonds@cs.ubc.ca>. 
950 (defun nnmail-article-group (func)
951   "Look at the headers and return an alist of groups that match.
952 FUNC will be called with the group name to determine the article number."
953   (let ((methods nnmail-split-methods)
954         (obuf (current-buffer))
955         (beg (point-min))
956         end group-art method)
957     (if (and (sequencep methods) (= (length methods) 1))
958         ;; If there is only just one group to put everything in, we
959         ;; just return a list with just this one method in.
960         (setq group-art
961               (list (cons (caar methods) (funcall func (caar methods)))))
962       ;; We do actual comparison.
963       (save-excursion
964         ;; Find headers.
965         (goto-char beg)
966         (setq end (if (search-forward "\n\n" nil t) (point) (point-max)))
967         (set-buffer nntp-server-buffer)
968         (erase-buffer)
969         ;; Copy the headers into the work buffer.
970         (insert-buffer-substring obuf beg end)
971         ;; Fold continuation lines.
972         (goto-char (point-min))
973         (while (re-search-forward "\\(\r?\n[ \t]+\\)+" nil t)
974           (replace-match " " t t))
975         ;; Allow washing.
976         (run-hooks 'nnmail-split-hook)
977         (if (and (symbolp nnmail-split-methods)
978                  (fboundp nnmail-split-methods))
979             (let ((split
980                    (condition-case nil
981                        (or (funcall nnmail-split-methods)
982                            '("bogus"))
983                      (error
984                       (message 
985                        "Error in `nnmail-split-methods'; using `bogus' mail group")
986                       (sit-for 1)
987                       '("bogus")))))
988               (unless (equal split '(junk))
989                 ;; `nnmail-split-methods' is a function, so we just call 
990                 ;; this function here and use the result.
991                 (setq group-art
992                       (mapcar
993                        (lambda (group) (cons group (funcall func group)))
994                        split))))
995           ;; Go through the split methods to find a match.
996           (while (and methods (or nnmail-crosspost (not group-art)))
997             (goto-char (point-max))
998             (setq method (pop methods))
999             (if (or methods
1000                     (not (equal "" (nth 1 method))))
1001                 (when (and
1002                        (ignore-errors
1003                          (if (stringp (nth 1 method))
1004                              (re-search-backward (cadr method) nil t)
1005                            ;; Function to say whether this is a match.
1006                            (funcall (nth 1 method) (car method))))
1007                        ;; Don't enter the article into the same 
1008                        ;; group twice.
1009                        (not (assoc (car method) group-art)))
1010                   (push (cons (car method) (funcall func (car method)))
1011                         group-art))
1012               ;; This is the final group, which is used as a 
1013               ;; catch-all.
1014               (unless group-art
1015                 (setq group-art 
1016                       (list (cons (car method)
1017                                   (funcall func (car method)))))))))
1018         ;; See whether the split methods returned `junk'.
1019         (if (equal group-art '(junk))
1020             nil
1021           (nreverse (delq 'junk group-art)))))))
1022
1023 (defun nnmail-insert-lines ()
1024   "Insert how many lines there are in the body of the mail.
1025 Return the number of characters in the body."
1026   (let (lines chars)
1027     (save-excursion
1028       (goto-char (point-min))
1029       (when (search-forward "\n\n" nil t)
1030         (setq chars (- (point-max) (point)))
1031         (setq lines (count-lines (point) (point-max)))
1032         (forward-char -1)
1033         (save-excursion
1034           (when (re-search-backward "^Lines: " nil t)
1035             (delete-region (point) (progn (forward-line 1) (point)))))
1036         (beginning-of-line)
1037         (insert (format "Lines: %d\n" (max lines 0)))
1038         chars))))
1039
1040 (defun nnmail-insert-xref (group-alist)
1041   "Insert an Xref line based on the (group . article) alist."
1042   (save-excursion
1043     (goto-char (point-min))
1044     (when (search-forward "\n\n" nil t)
1045       (forward-char -1)
1046       (when (re-search-backward "^Xref: " nil t)
1047         (delete-region (match-beginning 0)
1048                        (progn (forward-line 1) (point))))
1049       (insert (format "Xref: %s" (system-name)))
1050       (while group-alist
1051         (insert (format " %s:%d" (caar group-alist) (cdar group-alist)))
1052         (setq group-alist (cdr group-alist)))
1053       (insert "\n"))))
1054
1055 ;;; Message washing functions
1056
1057 (defun nnmail-remove-leading-whitespace ()
1058   "Remove excessive whitespace from all headers."
1059   (goto-char (point-min))
1060   (while (re-search-forward "^\\([^ :]+: \\) +" nil t)
1061     (replace-match "\\1" t)))
1062
1063 (defun nnmail-remove-list-identifiers ()
1064   "Remove list identifiers from Subject headers."
1065   (let ((regexp (if (stringp nnmail-list-identifiers) nnmail-list-identifiers
1066                   (mapconcat 'identity nnmail-list-identifiers "\\|"))))
1067     (when regexp
1068       (goto-char (point-min))
1069       (when (re-search-forward
1070              (concat "^Subject: +\\(Re: +\\)?\\(" regexp "\\) *")
1071              nil t)
1072         (delete-region (match-beginning 2) (match-end 0))))))
1073
1074 (defun nnmail-remove-tabs ()
1075   "Translate TAB characters into SPACE characters."
1076   (subst-char-in-region (point-min) (point-max) ?\t ?  t))
1077
1078 ;;; Utility functions
1079
1080 ;; Written by byer@mv.us.adobe.com (Scott Byer).
1081 (defun nnmail-make-complex-temp-name (prefix)
1082   (let ((newname (make-temp-name prefix))
1083         (newprefix prefix))
1084     (while (file-exists-p newname)
1085       (setq newprefix (concat newprefix "x"))
1086       (setq newname (make-temp-name newprefix)))
1087     newname))
1088
1089 ;; Written by Per Abrahamsen <amanda@iesd.auc.dk>.
1090
1091 (defun nnmail-split-fancy ()
1092   "Fancy splitting method.
1093 See the documentation for the variable `nnmail-split-fancy' for documentation."
1094   (let ((syntab (syntax-table)))
1095     (unwind-protect
1096         (progn
1097           (set-syntax-table nnmail-split-fancy-syntax-table)
1098           (nnmail-split-it nnmail-split-fancy))
1099       (set-syntax-table syntab))))
1100
1101 (defvar nnmail-split-cache nil)
1102 ;; Alist of split expressions their equivalent regexps.
1103
1104 (defun nnmail-split-it (split)
1105   ;; Return a list of groups matching SPLIT.
1106   (cond
1107    ;; nil split
1108    ((null split)
1109     nil)
1110
1111    ;; A group name.  Do the \& and \N subs into the string.
1112    ((stringp split)
1113     (list (nnmail-expand-newtext split)))
1114
1115    ;; Junk the message.
1116    ((eq split 'junk)
1117     (list 'junk))
1118
1119    ;; Builtin & operation.
1120    ((eq (car split) '&)
1121     (apply 'nconc (mapcar 'nnmail-split-it (cdr split))))
1122
1123    ;; Builtin | operation.
1124    ((eq (car split) '|)
1125     (let (done)
1126       (while (and (not done) (cdr split))
1127         (setq split (cdr split)
1128               done (nnmail-split-it (car split))))
1129       done))
1130
1131    ;; Builtin : operation.
1132    ((eq (car split) ':)
1133     (nnmail-split-it (eval (cdr split))))
1134
1135    ;; Check the cache for the regexp for this split.
1136    ;; FIX FIX FIX could avoid calling assq twice here
1137    ((assq split nnmail-split-cache)
1138     (goto-char (point-max))
1139     ;; FIX FIX FIX problem with re-search-backward is that if you have
1140     ;; a split: (from "foo-\\(bar\\|baz\\)@gnus.org "mail.foo.\\1")
1141     ;; and someone mails a message with 'To: foo-bar@gnus.org' and
1142     ;; 'CC: foo-baz@gnus.org', we'll pick 'mail.foo.baz' as the group
1143     ;; if the cc line is a later header, even though the other choice
1144     ;; is probably better.  Also, this routine won't do a crosspost
1145     ;; when there are two different matches.
1146     ;; I guess you could just make this more determined, and it could
1147     ;; look for still more matches prior to this one, and recurse
1148     ;; on each of the multiple matches hit.  Of course, then you'd
1149     ;; want to make sure that nnmail-article-group or nnmail-split-fancy
1150     ;; removed duplicates, since there might be more of those.
1151     ;; I guess we could also remove duplicates in the & split case, since
1152     ;; that's the only thing that can introduce them.
1153     (when (re-search-backward (cdr (assq split nnmail-split-cache)) nil t)
1154       ;; Someone might want to do a \N sub on this match, so get the
1155       ;; correct match positions.
1156       (goto-char (match-end 0))
1157       (let ((value (nth 1 split)))
1158         (re-search-backward (if (symbolp value)
1159                                 (cdr (assq value nnmail-split-abbrev-alist))
1160                               value)
1161                             (match-end 1)))
1162       (nnmail-split-it (nth 2 split))))
1163
1164    ;; Not in cache, compute a regexp for the field/value pair.
1165    (t
1166     (let* ((field (nth 0 split))
1167            (value (nth 1 split))
1168            (regexp (concat "^\\(\\("
1169                            (if (symbolp field)
1170                                (cdr (assq field nnmail-split-abbrev-alist))
1171                              field)
1172                            "\\):.*\\)\\<\\("
1173                            (if (symbolp value)
1174                                (cdr (assq value nnmail-split-abbrev-alist))
1175                              value)
1176                            "\\)\\>")))
1177       (push (cons split regexp) nnmail-split-cache)
1178       ;; Now that it's in the cache, just call nnmail-split-it again
1179       ;; on the same split, which will find it immediately in the cache.
1180       (nnmail-split-it split)))))
1181
1182 (defun nnmail-expand-newtext (newtext)
1183   (let ((len (length newtext))
1184         (pos 0)
1185         c expanded beg N did-expand)
1186     (while (< pos len)
1187       (setq beg pos)
1188       (while (and (< pos len)
1189                   (not (= (aref newtext pos) ?\\)))
1190         (setq pos (1+ pos)))
1191       (unless (= beg pos)
1192         (push (substring newtext beg pos) expanded))
1193       (when (< pos len)
1194         ;; we hit a \, expand it.
1195         (setq did-expand t)
1196         (setq pos (1+ pos))
1197         (setq c (aref newtext pos))
1198         (if (not (or (= c ?\&)
1199                      (and (>= c ?1)
1200                           (<= c ?9))))
1201             ;; \ followed by some character we don't expand
1202             (push (char-to-string c) expanded)
1203           ;; \& or \N
1204           (if (= c ?\&)
1205               (setq N 0)
1206             (setq N (- c ?0)))
1207           (when (match-beginning N)
1208             (push (buffer-substring (match-beginning N) (match-end N))
1209                   expanded))))
1210       (setq pos (1+ pos)))
1211     (if did-expand
1212         (apply 'concat (nreverse expanded))
1213       newtext)))
1214
1215 ;; Get a list of spool files to read.
1216 (defun nnmail-get-spool-files (&optional group)
1217   (if (null nnmail-spool-file)
1218       ;; No spool file whatsoever.
1219       nil
1220     (let* ((procmails 
1221             ;; If procmail is used to get incoming mail, the files
1222             ;; are stored in this directory.
1223             (and (file-exists-p nnmail-procmail-directory)
1224                  (or (eq nnmail-spool-file 'procmail)
1225                      nnmail-use-procmail)
1226                  (directory-files 
1227                   nnmail-procmail-directory 
1228                   t (concat (if group (concat "^" group) "")
1229                             nnmail-procmail-suffix "$"))))
1230            (p procmails)
1231            (crash (when (and (file-exists-p nnmail-crash-box)
1232                              (> (nnheader-file-size
1233                                  (file-truename nnmail-crash-box))
1234                                 0))
1235                     (list nnmail-crash-box))))
1236       ;; Remove any directories that inadvertently match the procmail
1237       ;; suffix, which might happen if the suffix is "". 
1238       (while p
1239         (when (file-directory-p (car p))
1240           (setq procmails (delete (car p) procmails)))
1241         (setq p (cdr p)))
1242       ;; Return the list of spools.
1243       (append 
1244        crash
1245        (cond ((and group
1246                    (or (eq nnmail-spool-file 'procmail)
1247                        nnmail-use-procmail)
1248                    procmails)
1249               procmails)
1250              ((and group
1251                    (eq nnmail-spool-file 'procmail))
1252               nil)
1253              ((listp nnmail-spool-file)
1254               (nconc
1255                (apply 
1256                 'nconc
1257                 (mapcar 
1258                  (lambda (file)
1259                    (if (and (not (string-match "^po:" file))
1260                             (file-directory-p file))
1261                        (nnheader-directory-regular-files file)
1262                      (list file)))
1263                  nnmail-spool-file))
1264                procmails))
1265              ((stringp nnmail-spool-file)
1266               (if (and (not (string-match "^po:" nnmail-spool-file))
1267                        (file-directory-p nnmail-spool-file))
1268                   (nconc 
1269                    (nnheader-directory-regular-files nnmail-spool-file)
1270                    procmails)
1271                 (cons nnmail-spool-file procmails)))
1272              ((eq nnmail-spool-file 'pop)
1273               (cons (format "po:%s" (user-login-name)) procmails))
1274              (t
1275               procmails))))))
1276
1277 ;; Activate a backend only if it isn't already activated. 
1278 ;; If FORCE, re-read the active file even if the backend is 
1279 ;; already activated.
1280 (defun nnmail-activate (backend &optional force)
1281   (let (file timestamp file-time)
1282     (if (or (not (symbol-value (intern (format "%s-group-alist" backend))))
1283             force
1284             (and (setq file (ignore-errors
1285                               (symbol-value (intern (format "%s-active-file" 
1286                                                             backend)))))
1287                  (setq file-time (nth 5 (file-attributes file)))
1288                  (or (not
1289                       (setq timestamp
1290                             (condition-case ()
1291                                 (symbol-value (intern
1292                                                (format "%s-active-timestamp" 
1293                                                        backend)))
1294                               (error 'none))))
1295                      (not (consp timestamp))
1296                      (equal timestamp '(0 0))
1297                      (> (nth 0 file-time) (nth 0 timestamp))
1298                      (and (= (nth 0 file-time) (nth 0 timestamp))
1299                           (> (nth 1 file-time) (nth 1 timestamp))))))
1300         (save-excursion
1301           (or (eq timestamp 'none)
1302               (set (intern (format "%s-active-timestamp" backend)) 
1303 ;;; dmoore@ucsd.edu 25.10.96
1304 ;;; it's not always the case that current-time
1305 ;;; does correspond to changes in the file's time.  So just compare
1306 ;;; the file's new time against its own previous time.
1307 ;;;                (current-time)
1308                    file-time
1309                    ))
1310           (funcall (intern (format "%s-request-list" backend)))
1311 ;;; dmoore@ucsd.edu 25.10.96
1312 ;;; BACKEND-request-list already does this itself!
1313 ;;;       (set (intern (format "%s-group-alist" backend)) 
1314 ;;;            (nnmail-get-active))
1315           ))
1316     t))
1317
1318 (defun nnmail-message-id ()
1319   (concat "<" (message-unique-id) "@totally-fudged-out-message-id>"))
1320
1321 ;;;
1322 ;;; nnmail duplicate handling
1323 ;;;
1324
1325 (defvar nnmail-cache-buffer nil)
1326
1327 (defun nnmail-cache-open ()
1328   (if (or (not nnmail-treat-duplicates)
1329           (and nnmail-cache-buffer
1330                (buffer-name nnmail-cache-buffer)))
1331       ()                                ; The buffer is open.
1332     (save-excursion
1333       (set-buffer 
1334        (setq nnmail-cache-buffer 
1335              (get-buffer-create " *nnmail message-id cache*")))
1336       (buffer-disable-undo (current-buffer))
1337       (when (file-exists-p nnmail-message-id-cache-file)
1338         (nnheader-insert-file-contents nnmail-message-id-cache-file))
1339       (set-buffer-modified-p nil)
1340       (current-buffer))))
1341
1342 (defun nnmail-cache-close ()
1343   (when (and nnmail-cache-buffer
1344              nnmail-treat-duplicates
1345              (buffer-name nnmail-cache-buffer)
1346              (buffer-modified-p nnmail-cache-buffer))
1347     (save-excursion
1348       (set-buffer nnmail-cache-buffer)
1349       ;; Weed out the excess number of Message-IDs.
1350       (goto-char (point-max))
1351       (when (search-backward "\n" nil t nnmail-message-id-cache-length)
1352         (progn
1353           (beginning-of-line)
1354           (delete-region (point-min) (point))))
1355       ;; Save the buffer.
1356       (or (file-exists-p (file-name-directory nnmail-message-id-cache-file))
1357           (make-directory (file-name-directory nnmail-message-id-cache-file)
1358                           t))
1359       (nnmail-write-region (point-min) (point-max)
1360                            nnmail-message-id-cache-file nil 'silent)
1361       (set-buffer-modified-p nil)
1362       (setq nnmail-cache-buffer nil)
1363       ;;(kill-buffer (current-buffer))
1364       )))
1365
1366 (defun nnmail-cache-insert (id)
1367   (when nnmail-treat-duplicates
1368     (save-excursion
1369       (set-buffer nnmail-cache-buffer)
1370       (goto-char (point-max))
1371       (insert id "\n"))))
1372
1373 (defun nnmail-cache-id-exists-p (id)
1374   (when nnmail-treat-duplicates
1375     (save-excursion
1376       (set-buffer nnmail-cache-buffer)
1377       (goto-char (point-max))
1378       (search-backward id nil t))))
1379
1380 (defun nnmail-check-duplication (message-id func artnum-func)
1381   (run-hooks 'nnmail-prepare-incoming-message-hook)
1382   ;; If this is a duplicate message, then we do not save it.
1383   (let* ((duplication (nnmail-cache-id-exists-p message-id))
1384          (case-fold-search t)
1385          (action (when duplication
1386                    (cond
1387                     ((memq nnmail-treat-duplicates '(warn delete))
1388                      nnmail-treat-duplicates)
1389                     ((nnheader-functionp nnmail-treat-duplicates)
1390                      (funcall nnmail-treat-duplicates message-id))
1391                     (t
1392                      nnmail-treat-duplicates))))
1393          group-art)
1394     ;; Let the backend save the article (or not).
1395     (cond
1396      ((not duplication)
1397       (nnmail-cache-insert message-id)
1398       (funcall func (setq group-art
1399                           (nreverse (nnmail-article-group artnum-func)))))
1400      ((eq action 'delete)
1401       (setq group-art nil))
1402      ((eq action 'warn)
1403       ;; We insert a warning.
1404       (let ((case-fold-search t)
1405             (newid (nnmail-message-id)))
1406         (goto-char (point-min))
1407         (when (re-search-forward "^message-id:" nil t)
1408           (beginning-of-line)
1409           (insert "Original-"))
1410         (beginning-of-line)
1411         (insert 
1412          "Message-ID: " newid "\n"
1413          "Gnus-Warning: This is a duplicate of message " message-id "\n")
1414         (nnmail-cache-insert newid)
1415         (funcall func (setq group-art
1416                             (nreverse (nnmail-article-group artnum-func))))))
1417      (t
1418       (funcall func (setq group-art
1419                           (nreverse (nnmail-article-group artnum-func))))))
1420     ;; Add the group-art list to the history list.
1421     (if group-art
1422         (push group-art nnmail-split-history)
1423       (delete-region (point-min) (point-max)))))
1424
1425 ;;; Get new mail.
1426
1427 (defun nnmail-get-value (&rest args)
1428   (let ((sym (intern (apply 'format args))))
1429     (when (boundp sym)
1430       (symbol-value sym))))
1431
1432 (defun nnmail-get-new-mail (method exit-func temp
1433                                    &optional group spool-func)
1434   "Read new incoming mail."
1435   ;; Nix out the previous split history.
1436   (unless group
1437     (setq nnmail-split-history nil))
1438   (let* ((spools (nnmail-get-spool-files group))
1439          (group-in group)
1440          incoming incomings spool)
1441     (when (and (nnmail-get-value "%s-get-new-mail" method)
1442                nnmail-spool-file)
1443       ;; We first activate all the groups.
1444       (nnmail-activate method)
1445       ;; Allow the user to hook.
1446       (run-hooks 'nnmail-pre-get-new-mail-hook)
1447       ;; Open the message-id cache.
1448       (nnmail-cache-open)
1449       ;; The we go through all the existing spool files and split the
1450       ;; mail from each.
1451       (while spools
1452         (setq spool (pop spools))
1453         ;; We read each spool file if either the spool is a POP-mail
1454         ;; spool, or the file exists.  We can't check for the
1455         ;; existence of POPped mail.
1456         (when (or (string-match "^po:" spool)
1457                   (and (file-exists-p (file-truename spool))
1458                        (> (nnheader-file-size (file-truename spool)) 0)))
1459           (nnheader-message 3 "%s: Reading incoming mail..." method)
1460           (when (and (nnmail-move-inbox spool)
1461                      (file-exists-p nnmail-crash-box))
1462             ;; There is new mail.  We first find out if all this mail
1463             ;; is supposed to go to some specific group.
1464             (setq group (nnmail-get-split-group spool group-in))
1465             ;; We split the mail
1466             (nnmail-split-incoming 
1467              nnmail-crash-box (intern (format "%s-save-mail" method))
1468              spool-func group (intern (format "%s-active-number" method)))
1469             ;; Check whether the inbox is to be moved to the special tmp dir. 
1470             (setq incoming
1471                   (nnmail-make-complex-temp-name 
1472                    (expand-file-name 
1473                     (if nnmail-tmp-directory
1474                         (concat 
1475                          (file-name-as-directory nnmail-tmp-directory)
1476                          (file-name-nondirectory (concat temp "Incoming")))
1477                       (concat temp "Incoming")))))
1478             (rename-file nnmail-crash-box incoming t)
1479             (push incoming incomings))))
1480       ;; If we did indeed read any incoming spools, we save all info. 
1481       (when incomings
1482         (nnmail-save-active 
1483          (nnmail-get-value "%s-group-alist" method)
1484          (nnmail-get-value "%s-active-file" method))
1485         (when exit-func
1486           (funcall exit-func))
1487         (run-hooks 'nnmail-read-incoming-hook)
1488         (nnheader-message 3 "%s: Reading incoming mail...done" method))
1489       ;; Close the message-id cache.
1490       (nnmail-cache-close)
1491       ;; Allow the user to hook.
1492       (run-hooks 'nnmail-post-get-new-mail-hook)
1493       ;; Delete all the temporary files.
1494       (while incomings
1495         (setq incoming (pop incomings))
1496         (and nnmail-delete-incoming
1497              (file-exists-p incoming)
1498              (file-writable-p incoming)
1499              (delete-file incoming))))))
1500
1501 (defun nnmail-expired-article-p (group time force &optional inhibit)
1502   "Say whether an article that is TIME old in GROUP should be expired."
1503   (if force
1504       t
1505     (let ((days (or (and nnmail-expiry-wait-function
1506                          (funcall nnmail-expiry-wait-function group))
1507                     nnmail-expiry-wait)))
1508       (cond ((or (eq days 'never)
1509                  (and (not force)
1510                       inhibit))
1511              ;; This isn't an expirable group.
1512              nil)
1513             ((eq days 'immediate)
1514              ;; We expire all articles on sight.
1515              t)
1516             ((equal time '(0 0))
1517              ;; This is an ange-ftp group, and we don't have any dates.
1518              nil)
1519             ((numberp days)
1520              (setq days (nnmail-days-to-time days))
1521              ;; Compare the time with the current time.
1522              (nnmail-time-less days (nnmail-time-since time)))))))
1523
1524 (defvar nnmail-read-passwd nil)
1525 (defun nnmail-read-passwd (prompt &rest args)
1526   "Read a password using PROMPT.
1527 If ARGS, PROMPT is used as an argument to `format'."
1528   (let ((prompt
1529          (if args
1530              (apply 'format prompt args)
1531            prompt)))
1532     (unless nnmail-read-passwd
1533       (if (load "passwd" t)
1534           (setq nnmail-read-passwd 'read-passwd)
1535         (autoload 'ange-ftp-read-passwd "ange-ftp")
1536         (setq nnmail-read-passwd 'ange-ftp-read-passwd)))
1537     (funcall nnmail-read-passwd prompt)))
1538
1539 (defun nnmail-check-syntax ()
1540   "Check (and modify) the syntax of the message in the current buffer."
1541   (save-restriction
1542     (message-narrow-to-head)
1543     (let ((case-fold-search t))
1544       (unless (re-search-forward "^Message-ID:" nil t)
1545         (insert "Message-ID: " (nnmail-message-id) "\n")))))
1546
1547 (defun nnmail-write-region (start end filename &optional append visit lockname)
1548   "Do a `write-region', and then set the file modes."
1549   (write-region start end filename append visit lockname)
1550   (set-file-modes filename nnmail-default-file-modes))
1551
1552 ;;;
1553 ;;; Status functions
1554 ;;;
1555
1556 (defun nnmail-replace-status (name value)
1557   "Make status NAME and VALUE part of the current status line."
1558   (save-restriction
1559     (message-narrow-to-head)
1560     (let ((status (nnmail-decode-status)))
1561       (setq status (delq (member name status) status))
1562       (when value
1563         (push (cons name value) status))
1564       (message-remove-header "status")
1565       (goto-char (point-max))
1566       (insert "Status: " (nnmail-encode-status status) "\n"))))
1567
1568 (defun nnmail-decode-status ()
1569   "Return a status-value alist from STATUS."
1570   (goto-char (point-min))
1571   (when (re-search-forward "^Status: " nil t)
1572     (let (name value status)
1573       (save-restriction
1574         ;; Narrow to the status.
1575         (narrow-to-region
1576          (point)
1577          (if (re-search-forward "^[^ \t]" nil t)
1578              (1- (point))
1579            (point-max)))
1580         ;; Go through all elements and add them to the list.
1581         (goto-char (point-min))
1582         (while (re-search-forward "[^ \t=]+" nil t)
1583           (setq name (match-string 0))
1584           (if (not (= (following-char) ?=))
1585               ;; Implied "yes".
1586               (setq value "yes")
1587             (forward-char 1)
1588             (if (not (= (following-char) ?\"))
1589                 (if (not (looking-at "[^ \t]"))
1590                     ;; Implied "no".
1591                     (setq value "no")
1592                   ;; Unquoted value.
1593                   (setq value (match-string 0))
1594                   (goto-char (match-end 0)))
1595               ;; Quoted value.
1596               (setq value (read (current-buffer)))))
1597           (push (cons name value) status)))
1598       status)))
1599
1600 (defun nnmail-encode-status (status)
1601   "Return a status string from STATUS."
1602   (mapconcat
1603    (lambda (elem)
1604      (concat
1605       (car elem) "="
1606       (if (string-match "[ \t]" (cdr elem))
1607           (prin1-to-string (cdr elem))
1608         (cdr elem))))
1609    status " "))
1610
1611 (defun nnmail-split-history ()
1612   "Generate an overview of where the last mail split put articles."
1613   (interactive)
1614   (unless nnmail-split-history
1615     (error "No current split history"))
1616   (with-output-to-temp-buffer "*nnmail split history*"
1617     (let ((history nnmail-split-history)
1618           elem)
1619       (while (setq elem (pop history))
1620         (princ (mapconcat (lambda (ga)
1621                             (concat (car ga) ":" (int-to-string (cdr ga))))
1622                           elem
1623                           ", "))
1624         (princ "\n")))))
1625
1626 (defun nnmail-new-mail-p (group)
1627   "Say whether GROUP has new mail."
1628   (let ((his nnmail-split-history)
1629         found)
1630     (while his
1631       (when (assoc group (pop his))
1632         (setq found t
1633               his nil)))
1634     found))
1635         
1636 (run-hooks 'nnmail-load-hook)
1637             
1638 (provide 'nnmail)
1639
1640 ;;; nnmail.el ends here