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