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