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