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