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