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