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