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