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