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