Importing pgnus-0.18.
[elisp/gnus.git-] / lisp / nnmail.el
1 ;;; nnmail.el --- mail support functions for the Gnus mail backends
2 ;; Copyright (C) 1995,96,97,98 Free Software Foundation, Inc.
3
4 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
5 ;; Keywords: news, mail
6
7 ;; This file is part of GNU Emacs.
8
9 ;; GNU Emacs is free software; you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation; either version 2, or (at your option)
12 ;; any later version.
13
14 ;; GNU Emacs is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 ;; GNU General Public License for more details.
18
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
21 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
22 ;; Boston, MA 02111-1307, USA.
23
24 ;;; Commentary:
25
26 ;;; Code:
27
28 (eval-when-compile (require 'cl))
29
30 (require 'nnheader)
31 (require 'message)
32 (require 'custom)
33 (require 'gnus-util)
34
35 (eval-and-compile
36   (autoload 'gnus-error "gnus-util")
37   (autoload 'gnus-buffer-live-p "gnus-util"))
38
39 (defgroup nnmail nil
40   "Reading mail with Gnus."
41   :group 'gnus)
42
43 (defgroup nnmail-retrieve nil
44   "Retrieving new mail."
45   :group 'nnmail)
46
47 (defgroup nnmail-prepare nil
48   "Preparing (or mangling) new mail after retrival."
49   :group 'nnmail)
50
51 (defgroup nnmail-duplicate nil
52   "Handling of duplicate mail messages."
53   :group 'nnmail)
54
55 (defgroup nnmail-split nil
56   "Organizing the incomming mail in folders."
57   :group 'nnmail)
58
59 (defgroup nnmail-files nil
60   "Mail files."
61   :group 'gnus-files
62   :group 'nnmail)
63
64 (defgroup nnmail-expire nil
65   "Expiring old mail."
66   :group 'nnmail)
67
68 (defgroup nnmail-procmail nil
69   "Interfacing with procmail and other mail agents."
70   :group 'nnmail)
71
72 (defgroup nnmail-various nil
73   "Various mail options."
74   :group 'nnmail)
75
76 (defcustom nnmail-split-methods
77   '(("mail.misc" ""))
78   "*Incoming mail will be split according to this variable.
79
80 If you'd like, for instance, one mail group for mail from the
81 \"4ad-l\" mailing list, one group for junk mail and one for everything
82 else, you could do something like this:
83
84  (setq nnmail-split-methods
85        '((\"mail.4ad\" \"From:.*4ad\")
86          (\"mail.junk\" \"From:.*Lars\\\\|Subject:.*buy\")
87          (\"mail.misc\" \"\")))
88
89 As you can see, this variable is a list of lists, where the first
90 element in each \"rule\" is the name of the group (which, by the way,
91 does not have to be called anything beginning with \"mail\",
92 \"yonka.zow\" is a fine, fine name), and the second is a regexp that
93 nnmail will try to match on the header to find a fit.
94
95 The second element can also be a function.  In that case, it will be
96 called narrowed to the headers with the first element of the rule as
97 the argument.  It should return a non-nil value if it thinks that the
98 mail belongs in that group.
99
100 The last element should always have \"\" as the regexp.
101
102 This variable can also have a function as its value."
103   :group 'nnmail-split
104   :type '(choice (repeat :tag "Alist" (group (string :tag "Name") regexp))
105                  (function-item nnmail-split-fancy)
106                  (function :tag "Other")))
107
108 ;; Suggested by Erik Selberg <speed@cs.washington.edu>.
109 (defcustom nnmail-crosspost t
110   "If non-nil, do crossposting if several split methods match the mail.
111 If nil, the first match found will be used."
112   :group 'nnmail-split
113   :type 'boolean)
114
115 ;; Added by gord@enci.ucalgary.ca (Gordon Matzigkeit).
116 (defcustom nnmail-keep-last-article nil
117   "If non-nil, nnmail will never delete/move a group's last article.
118 It can be marked expirable, so it will be deleted when it is no longer last.
119
120 You may need to set this variable if other programs are putting
121 new mail into folder numbers that Gnus has marked as expired."
122   :group 'nnmail-procmail
123   :group 'nnmail-various
124   :type 'boolean)
125
126 (defcustom nnmail-use-long-file-names nil
127   "If non-nil the mail backends will use long file and directory names.
128 If nil, groups like \"mail.misc\" will end up in directories like
129 \"mail/misc/\"."
130   :group 'nnmail-files
131   :type 'boolean)
132
133 (defcustom nnmail-default-file-modes 384
134   "Set the mode bits of all new mail files to this integer."
135   :group 'nnmail-files
136   :type 'integer)
137
138 (defcustom nnmail-expiry-wait 7
139   "*Expirable articles that are older than this will be expired.
140 This variable can either be a number (which will be interpreted as a
141 number of days) -- this doesn't have to be an integer.  This variable
142 can also be `immediate' and `never'."
143   :group 'nnmail-expire
144   :type '(choice (const immediate)
145                  (integer :tag "days")
146                  (const never)))
147
148 (defcustom nnmail-expiry-wait-function nil
149   "Variable that holds function to specify how old articles should be before they are expired.
150   The function will be called with the name of the group that the
151 expiry is to be performed in, and it should return an integer that
152 says how many days an article can be stored before it is considered
153 \"old\".  It can also return the values `never' and `immediate'.
154
155 Eg.:
156
157 \(setq nnmail-expiry-wait-function
158       (lambda (newsgroup)
159         (cond ((string-match \"private\" newsgroup) 31)
160               ((string-match \"junk\" newsgroup) 1)
161               ((string-match \"important\" newsgroup) 'never)
162               (t 7))))"
163   :group 'nnmail-expire
164   :type '(choice (const :tag "nnmail-expiry-wait" nil)
165                  (function :format "%v" nnmail-)))
166
167 (defcustom nnmail-cache-accepted-message-ids nil
168   "If non-nil, put Message-IDs of Gcc'd articles into the duplicate cache."
169   :group 'nnmail
170   :type 'boolean)
171
172 (defcustom nnmail-spool-file
173   (or (getenv "MAIL")
174       (concat "/usr/spool/mail/" (user-login-name)))
175   "*Where the mail backends will look for incoming mail.
176 This variable is \"/usr/spool/mail/$user\" by default.
177 If this variable is nil, no mail backends will read incoming mail.
178 If this variable is a list, all files mentioned in this list will be
179 used as incoming mailboxes.
180 If this variable is a directory (i. e., it's name ends with a \"/\"),
181 treat all files in that directory as incoming spool files."
182   :group 'nnmail-files
183   :type '(choice (file :tag "File")
184                  (repeat :tag "Files" file)))
185
186 (defcustom nnmail-crash-box "~/.gnus-crash-box"
187   "File where Gnus will store mail while processing it."
188   :group 'nnmail-files
189   :type 'file)
190
191 (defcustom nnmail-use-procmail nil
192   "*If non-nil, the mail backends will look in `nnmail-procmail-directory' for spool files.
193 The file(s) in `nnmail-spool-file' will also be read."
194   :group 'nnmail-procmail
195   :type 'boolean)
196
197 (defcustom nnmail-procmail-directory "~/incoming/"
198   "*When using procmail (and the like), incoming mail is put in this directory.
199 The Gnus mail backends will read the mail from this directory."
200   :group 'nnmail-procmail
201   :type 'directory)
202
203 (defcustom nnmail-procmail-suffix "\\.spool"
204   "*Suffix of files created by procmail (and the like).
205 This variable might be a suffix-regexp to match the suffixes of
206 several files - eg. \".spool[0-9]*\"."
207   :group 'nnmail-procmail
208   :type 'regexp)
209
210 (defcustom nnmail-resplit-incoming nil
211   "*If non-nil, re-split incoming procmail sorted mail."
212   :group 'nnmail-procmail
213   :type 'boolean)
214
215 (defcustom nnmail-delete-file-function 'delete-file
216   "Function called to delete files in some mail backends."
217   :group 'nnmail-files
218   :type 'function)
219
220 (defcustom nnmail-crosspost-link-function
221   (if (string-match "windows-nt\\|emx" (symbol-name system-type))
222       'copy-file
223     'add-name-to-file)
224   "*Function called to create a copy of a file.
225 This is `add-name-to-file' by default, which means that crossposts
226 will use hard links.  If your file system doesn't allow hard
227 links, you could set this variable to `copy-file' instead."
228   :group 'nnmail-files
229   :type '(radio (function-item add-name-to-file)
230                 (function-item copy-file)
231                 (function :tag "Other")))
232
233 (defcustom nnmail-movemail-program "movemail"
234   "*A command to be executed to move mail from the inbox.
235 The default is \"movemail\".
236
237 This can also be a function.  In that case, the function will be
238 called with two parameters -- the name of the INBOX file, and the file
239 to be moved to."
240   :group 'nnmail-files
241   :group 'nnmail-retrieve
242   :type 'string)
243
244 (defcustom nnmail-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   (erase-buffer)
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               (pathname-coding-system nnmail-file-coding-system))
496           (insert-file-contents file)
497           t)
498       (file-error nil))))
499
500 (defvar nnmail-pathname-coding-system
501   'iso-8859-1
502   "*Coding system for pathname.")
503
504 (defun nnmail-group-pathname (group dir &optional file)
505   "Make pathname for GROUP."
506   (concat
507    (let ((dir (file-name-as-directory (expand-file-name dir))))
508      (setq group (nnheader-translate-file-chars group))
509      ;; If this directory exists, we use it directly.
510      (if (or nnmail-use-long-file-names
511              (file-directory-p (concat dir group)))
512          (concat dir group "/")
513        ;; If not, we translate dots into slashes.
514        (concat dir
515                (nnheader-encode-coding-string
516                 (nnheader-replace-chars-in-string group ?. ?/)
517                 nnmail-pathname-coding-system)
518                "/")))
519    (or file "")))
520
521 ;; Function rewritten from rmail.el.
522 (defun nnmail-move-inbox (inbox)
523   "Move INBOX to `nnmail-crash-box'."
524   (if (not (file-writable-p nnmail-crash-box))
525       (gnus-error 1 "Can't write to crash box %s.  Not moving mail"
526                   nnmail-crash-box)
527     ;; If the crash box exists and is empty, we delete it.
528     (when (and (file-exists-p nnmail-crash-box)
529                (zerop (nnheader-file-size (file-truename nnmail-crash-box))))
530       (delete-file nnmail-crash-box))
531     (let ((tofile (file-truename (expand-file-name nnmail-crash-box)))
532           (popmail (string-match "^po:" inbox))
533           movemail errors result)
534       (unless popmail
535         (setq inbox (file-truename (expand-file-name inbox)))
536         (setq movemail t)
537         ;; On some systems, /usr/spool/mail/foo is a directory
538         ;; and the actual inbox is /usr/spool/mail/foo/foo.
539         (when (file-directory-p inbox)
540           (setq inbox (expand-file-name (user-login-name) inbox))))
541       (if (member inbox nnmail-moved-inboxes)
542           ;; We don't try to move an already moved inbox.
543           nil
544         (if popmail
545             (progn
546               (when (and nnmail-pop-password
547                          (not nnmail-internal-password))
548                 (setq nnmail-internal-password nnmail-pop-password))
549               (when (and nnmail-pop-password-required
550                          (not nnmail-internal-password))
551                 (setq nnmail-internal-password
552                       (nnmail-read-passwd
553                        (format "Password for %s: "
554                                (substring inbox (+ popmail 3))))))
555               (nnheader-message 5 "Getting mail from the post office..."))
556           (when (or (and (file-exists-p tofile)
557                          (/= 0 (nnheader-file-size tofile)))
558                     (and (file-exists-p inbox)
559                          (/= 0 (nnheader-file-size inbox))))
560             (nnheader-message 5 "Getting mail from %s..." inbox)))
561         ;; Set TOFILE if have not already done so, and
562         ;; rename or copy the file INBOX to TOFILE if and as appropriate.
563         (cond
564          ((file-exists-p tofile)
565           ;; The crash box exists already.
566           t)
567          ((and (not popmail)
568                (not (file-exists-p inbox)))
569           ;; There is no inbox.
570           (setq tofile nil))
571          (t
572           ;; If getting from mail spool directory, use movemail to move
573           ;; rather than just renaming, so as to interlock with the
574           ;; mailer.
575           (unwind-protect
576               (save-excursion
577                 (setq errors (generate-new-buffer " *nnmail loss*"))
578                 (buffer-disable-undo errors)
579                 (if (nnheader-functionp nnmail-movemail-program)
580                     (condition-case err
581                         (progn
582                           (funcall nnmail-movemail-program inbox tofile)
583                           (setq result 0))
584                       (error
585                        (save-excursion
586                          (set-buffer errors)
587                          (insert (prin1-to-string err))
588                          (setq result 255))))
589                   (let ((default-directory "/"))
590                     (setq result
591                           (apply
592                            'call-process
593                            (append
594                             (list
595                              (expand-file-name
596                               nnmail-movemail-program exec-directory)
597                              nil errors nil inbox tofile)
598                             (when nnmail-internal-password
599                               (list nnmail-internal-password)))))))
600                 (push inbox nnmail-moved-inboxes)
601                 (if (and (not (buffer-modified-p errors))
602                          (zerop result))
603                     ;; No output => movemail won
604                     (progn
605                       (unless popmail
606                         (when (file-exists-p tofile)
607                           (set-file-modes tofile nnmail-default-file-modes))))
608                   (set-buffer errors)
609                   ;; There may be a warning about older revisions.  We
610                   ;; ignore those.
611                   (goto-char (point-min))
612                   (if (search-forward "older revision" nil t)
613                       (progn
614                         (unless popmail
615                           (when (file-exists-p tofile)
616                             (set-file-modes
617                              tofile nnmail-default-file-modes))))
618                     ;; Probably a real error.
619                     ;; We nix out the password in case the error
620                     ;; was because of a wrong password being given.
621                     (setq nnmail-internal-password nil)
622                     (subst-char-in-region (point-min) (point-max) ?\n ?\  )
623                     (goto-char (point-max))
624                     (skip-chars-backward " \t")
625                     (delete-region (point) (point-max))
626                     (goto-char (point-min))
627                     (when (looking-at "movemail: ")
628                       (delete-region (point-min) (match-end 0)))
629                     (unless (yes-or-no-p
630                              (format "movemail: %s (%d return).  Continue? "
631                                      (buffer-string) result))
632                       (error "%s" (buffer-string)))
633                     (setq tofile nil)))))))
634         (nnheader-message 5 "Getting mail from %s...done" inbox)
635         (and errors
636              (buffer-name errors)
637              (kill-buffer errors))
638         tofile))))
639
640 (defun nnmail-get-active ()
641   "Returns an assoc of group names and active ranges.
642 nn*-request-list should have been called before calling this function."
643   (let (group-assoc)
644     ;; Go through all groups from the active list.
645     (save-excursion
646       (set-buffer nntp-server-buffer)
647       (goto-char (point-min))
648       (while (re-search-forward
649               "^\\([^ \t]+\\)[ \t]+\\([0-9]+\\)[ \t]+\\([0-9]+\\)" nil t)
650         ;; We create an alist with `(GROUP (LOW . HIGH))' elements.
651         (push (list (match-string 1)
652                     (cons (string-to-int (match-string 3))
653                           (string-to-int (match-string 2))))
654               group-assoc)))
655     group-assoc))
656
657 (defvar nnmail-active-file-coding-system 'binary
658   "*Coding system for active file.")
659
660 (defun nnmail-save-active (group-assoc file-name)
661   "Save GROUP-ASSOC in ACTIVE-FILE."
662   (let ((coding-system-for-write nnmail-active-file-coding-system))
663     (when file-name
664       (with-temp-file file-name
665         (nnmail-generate-active group-assoc)))))
666
667 (defun nnmail-generate-active (alist)
668   "Generate an active file from group-alist ALIST."
669   (erase-buffer)
670   (let (group)
671     (while (setq group (pop alist))
672       (insert (format "%s %d %d y\n" (car group) (cdadr group)
673                       (caadr group))))))
674
675 (defun nnmail-get-split-group (file group)
676   "Find out whether this FILE is to be split into GROUP only.
677 If GROUP is non-nil and we are using procmail, return the group name
678 only when the file is the correct procmail file.  When GROUP is nil,
679 return nil if FILE is a spool file or the procmail group for which it
680 is a spool.  If not using procmail, return GROUP."
681   (if (or (eq nnmail-spool-file 'procmail)
682           nnmail-use-procmail)
683       (if (string-match (concat "^" (regexp-quote
684                                      (expand-file-name
685                                       (file-name-as-directory
686                                        nnmail-procmail-directory)))
687                                 "\\([^/]*\\)"
688                                 nnmail-procmail-suffix "$")
689                         (expand-file-name file))
690           (let ((procmail-group (substring (expand-file-name file)
691                                            (match-beginning 1)
692                                            (match-end 1))))
693             (if group
694                 (if (string-equal group procmail-group)
695                     group
696                   nil)
697               procmail-group))
698         nil)
699     group))
700
701 (defun nnmail-process-babyl-mail-format (func artnum-func)
702   (let ((case-fold-search t)
703         start message-id content-length do-search end)
704     (while (not (eobp))
705       (goto-char (point-min))
706       (re-search-forward
707        "\f\n0, *unseen,+\n\\(\\*\\*\\* EOOH \\*\\*\\*\n\\)?" nil t)
708       (goto-char (match-end 0))
709       (delete-region (match-beginning 0) (match-end 0))
710       (narrow-to-region
711        (setq start (point))
712        (progn
713          ;; Skip all the headers in case there are more "From "s...
714          (or (search-forward "\n\n" nil t)
715              (search-forward-regexp "^[^:]*\\( .*\\|\\)$" nil t)
716              (search-forward "\1f\f"))
717          (point)))
718       ;; Unquote the ">From " line, if any.
719       (goto-char (point-min))
720       (when (looking-at ">From ")
721         (replace-match "X-From-Line: ") )
722       (run-hooks 'nnmail-prepare-incoming-header-hook)
723       (goto-char (point-max))
724       ;; Find the Message-ID header.
725       (save-excursion
726         (if (re-search-backward
727              "^Message-ID[ \t]*:[ \n\t]*\\(<[^>]*>\\)" nil t)
728             (setq message-id (buffer-substring (match-beginning 1)
729                                                (match-end 1)))
730           ;; There is no Message-ID here, so we create one.
731           (save-excursion
732             (when (re-search-backward "^Message-ID[ \t]*:" nil t)
733               (beginning-of-line)
734               (insert "Original-")))
735           (forward-line -1)
736           (insert "Message-ID: " (setq message-id (nnmail-message-id))
737                   "\n")))
738       ;; Look for a Content-Length header.
739       (if (not (save-excursion
740                  (and (re-search-backward
741                        "^Content-Length:[ \t]*\\([0-9]+\\)" start t)
742                       (setq content-length (string-to-int
743                                             (buffer-substring
744                                              (match-beginning 1)
745                                              (match-end 1))))
746                       ;; We destroy the header, since none of
747                       ;; the backends ever use it, and we do not
748                       ;; want to confuse other mailers by having
749                       ;; a (possibly) faulty header.
750                       (progn (insert "X-") t))))
751           (setq do-search t)
752         (widen)
753         (if (or (= (+ (point) content-length) (point-max))
754                 (save-excursion
755                   (goto-char (+ (point) content-length))
756                   (looking-at "\1f")))
757             (progn
758               (goto-char (+ (point) content-length))
759               (setq do-search nil))
760           (setq do-search t)))
761       (widen)
762       ;; Go to the beginning of the next article - or to the end
763       ;; of the buffer.
764       (when do-search
765         (if (re-search-forward "^\1f" nil t)
766             (goto-char (match-beginning 0))
767           (goto-char (1- (point-max)))))
768       (delete-char 1)                   ; delete ^_
769       (save-excursion
770         (save-restriction
771           (narrow-to-region start (point))
772           (goto-char (point-min))
773           (nnmail-check-duplication message-id func artnum-func)
774           (setq end (point-max))))
775       (goto-char end))))
776
777 (defsubst nnmail-search-unix-mail-delim ()
778   "Put point at the beginning of the next Unix mbox message."
779   ;; Algorithm used to find the the next article in the
780   ;; brain-dead Unix mbox format:
781   ;;
782   ;; 1) Search for "^From ".
783   ;; 2) If we find it, then see whether the previous
784   ;;    line is blank and the next line looks like a header.
785   ;; Then it's possible that this is a mail delim, and we use it.
786   (let ((case-fold-search nil)
787         found)
788     (while (not found)
789       (if (not (re-search-forward "^From " nil t))
790           (setq found 'no)
791         (save-excursion
792           (beginning-of-line)
793           (when (and (or (bobp)
794                          (save-excursion
795                            (forward-line -1)
796                            (= (following-char) ?\n)))
797                      (save-excursion
798                        (forward-line 1)
799                        (while (looking-at ">From \\|From ")
800                          (forward-line 1))
801                        (looking-at "[^ \n\t:]+[ \n\t]*:")))
802             (setq found 'yes)))))
803     (beginning-of-line)
804     (eq found 'yes)))
805
806 (defun nnmail-search-unix-mail-delim-backward ()
807   "Put point at the beginning of the current Unix mbox message."
808   ;; Algorithm used to find the the next article in the
809   ;; brain-dead Unix mbox format:
810   ;;
811   ;; 1) Search for "^From ".
812   ;; 2) If we find it, then see whether the previous
813   ;;    line is blank and the next line looks like a header.
814   ;; Then it's possible that this is a mail delim, and we use it.
815   (let ((case-fold-search nil)
816         found)
817     (while (not found)
818       (if (not (re-search-backward "^From " nil t))
819           (setq found 'no)
820         (save-excursion
821           (beginning-of-line)
822           (when (and (or (bobp)
823                          (save-excursion
824                            (forward-line -1)
825                            (= (following-char) ?\n)))
826                      (save-excursion
827                        (forward-line 1)
828                        (while (looking-at ">From \\|From ")
829                          (forward-line 1))
830                        (looking-at "[^ \n\t:]+[ \n\t]*:")))
831             (setq found 'yes)))))
832     (beginning-of-line)
833     (eq found 'yes)))
834
835 (defun nnmail-process-unix-mail-format (func artnum-func)
836   (let ((case-fold-search t)
837         start message-id content-length end skip head-end)
838     (goto-char (point-min))
839     (if (not (and (re-search-forward "^From " nil t)
840                   (goto-char (match-beginning 0))))
841         ;; Possibly wrong format?
842         (progn
843           (pop-to-buffer (nnheader-find-file-noselect nnmail-current-spool))
844           (error "Error, unknown mail format! (Possibly corrupted.)"))
845       ;; Carry on until the bitter end.
846       (while (not (eobp))
847         (setq start (point)
848               end nil)
849         ;; Find the end of the head.
850         (narrow-to-region
851          start
852          (if (search-forward "\n\n" nil t)
853              (1- (point))
854            ;; This will never happen, but just to be on the safe side --
855            ;; if there is no head-body delimiter, we search a bit manually.
856            (while (and (looking-at "From \\|[^ \t]+:")
857                        (not (eobp)))
858              (forward-line 1))
859            (point)))
860         ;; Find the Message-ID header.
861         (goto-char (point-min))
862         (if (re-search-forward "^Message-ID[ \t]*:[ \n\t]*\\(<[^>]+>\\)" nil t)
863             (setq message-id (match-string 1))
864           (save-excursion
865             (when (re-search-forward "^Message-ID[ \t]*:" nil t)
866               (beginning-of-line)
867               (insert "Original-")))
868           ;; There is no Message-ID here, so we create one.
869           (forward-line 1)
870           (insert "Message-ID: " (setq message-id (nnmail-message-id)) "\n"))
871         ;; Look for a Content-Length header.
872         (goto-char (point-min))
873         (if (not (re-search-forward
874                   "^Content-Length:[ \t]*\\([0-9]+\\)" nil t))
875             (setq content-length nil)
876           (setq content-length (string-to-int (match-string 1)))
877           ;; We destroy the header, since none of the backends ever
878           ;; use it, and we do not want to confuse other mailers by
879           ;; having a (possibly) faulty header.
880           (beginning-of-line)
881           (insert "X-"))
882         (run-hooks 'nnmail-prepare-incoming-header-hook)
883         ;; Find the end of this article.
884         (goto-char (point-max))
885         (widen)
886         (setq head-end (point))
887         ;; We try the Content-Length value.  The idea: skip over the header
888         ;; separator, then check what happens content-length bytes into the
889         ;; message body.  This should be either the end ot the buffer, the
890         ;; message separator or a blank line followed by the separator.
891         ;; The blank line should probably be deleted.  If neither of the
892         ;; three is met, the content-length header is probably invalid.
893         (when content-length
894           (forward-line 1)
895           (setq skip (+ (point) content-length))
896           (goto-char skip)
897           (cond ((or (= skip (point-max))
898                      (= (1+ skip) (point-max)))
899                  (setq end (point-max)))
900                 ((looking-at "From ")
901                  (setq end skip))
902                 ((looking-at "[ \t]*\n\\(From \\)")
903                  (setq end (match-beginning 1)))
904                 (t (setq end nil))))
905         (if end
906             (goto-char end)
907           ;; No Content-Length, so we find the beginning of the next
908           ;; article or the end of the buffer.
909           (goto-char head-end)
910           (or (nnmail-search-unix-mail-delim)
911               (goto-char (point-max))))
912         ;; Allow the backend to save the article.
913         (save-excursion
914           (save-restriction
915             (narrow-to-region start (point))
916             (goto-char (point-min))
917             (nnmail-check-duplication message-id func artnum-func)
918             (setq end (point-max))))
919         (goto-char end)))))
920
921 (defun nnmail-process-mmdf-mail-format (func artnum-func)
922   (let ((delim "^\^A\^A\^A\^A$")
923         (case-fold-search t)
924         start message-id end)
925     (goto-char (point-min))
926     (if (not (and (re-search-forward delim nil t)
927                   (forward-line 1)))
928         ;; Possibly wrong format?
929         (progn
930           (pop-to-buffer (nnheader-find-file-noselect nnmail-current-spool))
931           (error "Error, unknown mail format! (Possibly corrupted.)"))
932       ;; Carry on until the bitter end.
933       (while (not (eobp))
934         (setq start (point))
935         ;; Find the end of the head.
936         (narrow-to-region
937          start
938          (if (search-forward "\n\n" nil t)
939              (1- (point))
940            ;; This will never happen, but just to be on the safe side --
941            ;; if there is no head-body delimiter, we search a bit manually.
942            (while (and (looking-at "From \\|[^ \t]+:")
943                        (not (eobp)))
944              (forward-line 1))
945            (point)))
946         ;; Find the Message-ID header.
947         (goto-char (point-min))
948         (if (re-search-forward "^Message-ID[ \t]*:[ \n\t]*\\(<[^>]+>\\)" nil t)
949             (setq message-id (match-string 1))
950           ;; There is no Message-ID here, so we create one.
951           (save-excursion
952             (when (re-search-backward "^Message-ID[ \t]*:" nil t)
953               (beginning-of-line)
954               (insert "Original-")))
955           (forward-line 1)
956           (insert "Message-ID: " (setq message-id (nnmail-message-id)) "\n"))
957         (run-hooks 'nnmail-prepare-incoming-header-hook)
958         ;; Find the end of this article.
959         (goto-char (point-max))
960         (widen)
961         (if (re-search-forward delim nil t)
962             (beginning-of-line)
963           (goto-char (point-max)))
964         ;; Allow the backend to save the article.
965         (save-excursion
966           (save-restriction
967             (narrow-to-region start (point))
968             (goto-char (point-min))
969             (nnmail-check-duplication message-id func artnum-func)
970             (setq end (point-max))))
971         (goto-char end)
972         (forward-line 2)))))
973
974 (defun nnmail-split-incoming (incoming func &optional exit-func
975                                        group artnum-func)
976   "Go through the entire INCOMING file and pick out each individual mail.
977 FUNC will be called with the buffer narrowed to each mail."
978   (let (;; If this is a group-specific split, we bind the split
979         ;; methods to just this group.
980         (nnmail-split-methods (if (and group
981                                        (or (eq nnmail-spool-file 'procmail)
982                                            nnmail-use-procmail)
983                                        (not nnmail-resplit-incoming))
984                                   (list (list group ""))
985                                 nnmail-split-methods)))
986     (save-excursion
987       ;; Insert the incoming file.
988       (set-buffer (get-buffer-create " *nnmail incoming*"))
989       (buffer-disable-undo (current-buffer))
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                                   (replace-match
1099                                    (car method) nil nil (car method))
1100                                 (car method))
1101                               (funcall func (car method)))
1102                         group-art))
1103               ;; This is the final group, which is used as a
1104               ;; catch-all.
1105               (unless group-art
1106                 (setq group-art
1107                       (list (cons (car method)
1108                                   (funcall func (car method)))))))))
1109         ;; Produce a trace if non-empty.
1110         (when (and trace nnmail-split-trace)
1111           (let ((trace (nreverse nnmail-split-trace))
1112                 (restore (current-buffer)))
1113             (nnheader-set-temp-buffer "*Split Trace*")
1114             (gnus-add-buffer)
1115             (while trace
1116               (insert (car trace) "\n")
1117               (setq trace (cdr trace)))
1118             (goto-char (point-min))
1119             (gnus-configure-windows 'split-trace)
1120             (set-buffer restore)))
1121         ;; See whether the split methods returned `junk'.
1122         (if (equal group-art '(junk))
1123             nil
1124           ;; The article may be "cross-posted" to `junk'.  What
1125           ;; to do?  Just remove the `junk' spec.  Don't really
1126           ;; see anything else to do...
1127           (let (elem)
1128             (while (setq elem (car (memq 'junk group-art)))
1129               (setq group-art (delq elem group-art)))
1130             (nreverse group-art)))))))
1131
1132 (defun nnmail-insert-lines ()
1133   "Insert how many lines there are in the body of the mail.
1134 Return the number of characters in the body."
1135   (let (lines chars)
1136     (save-excursion
1137       (goto-char (point-min))
1138       (when (search-forward "\n\n" nil t)
1139         (setq chars (- (point-max) (point)))
1140         (setq lines (count-lines (point) (point-max)))
1141         (forward-char -1)
1142         (save-excursion
1143           (when (re-search-backward "^Lines: " nil t)
1144             (delete-region (point) (progn (forward-line 1) (point)))))
1145         (beginning-of-line)
1146         (insert (format "Lines: %d\n" (max lines 0)))
1147         chars))))
1148
1149 (defun nnmail-insert-xref (group-alist)
1150   "Insert an Xref line based on the (group . article) alist."
1151   (save-excursion
1152     (goto-char (point-min))
1153     (when (search-forward "\n\n" nil t)
1154       (forward-char -1)
1155       (when (re-search-backward "^Xref: " nil t)
1156         (delete-region (match-beginning 0)
1157                        (progn (forward-line 1) (point))))
1158       (insert (format "Xref: %s" (system-name)))
1159       (while group-alist
1160         (insert (format " %s:%d"
1161                         (nnheader-encode-coding-string
1162                          (caar group-alist)
1163                          nnmail-pathname-coding-system)
1164                         (cdar group-alist)))
1165         (setq group-alist (cdr group-alist)))
1166       (insert "\n"))))
1167
1168 ;;; Message washing functions
1169
1170 (defun nnmail-remove-leading-whitespace ()
1171   "Remove excessive whitespace from all headers."
1172   (goto-char (point-min))
1173   (while (re-search-forward "^\\([^ :]+: \\) +" nil t)
1174     (replace-match "\\1" t)))
1175
1176 (defun nnmail-remove-list-identifiers ()
1177   "Remove list identifiers from Subject headers."
1178   (let ((regexp (if (stringp nnmail-list-identifiers) nnmail-list-identifiers
1179                   (mapconcat 'identity nnmail-list-identifiers "\\|"))))
1180     (when regexp
1181       (goto-char (point-min))
1182       (when (re-search-forward
1183              (concat "^Subject: +\\(Re: +\\)?\\(" regexp "\\) *")
1184              nil t)
1185         (delete-region (match-beginning 2) (match-end 0))))))
1186
1187 (defun nnmail-remove-tabs ()
1188   "Translate TAB characters into SPACE characters."
1189   (subst-char-in-region (point-min) (point-max) ?\t ?  t))
1190
1191 ;;; Utility functions
1192
1193 (defun nnmail-make-complex-temp-name (prefix)
1194   (let ((newname (make-temp-name prefix))
1195         (newprefix prefix))
1196     (while (file-exists-p newname)
1197       (setq newprefix (concat newprefix "x"))
1198       (setq newname (make-temp-name newprefix)))
1199     newname))
1200
1201 ;; Written by Per Abrahamsen <amanda@iesd.auc.dk>.
1202
1203 (defun nnmail-split-fancy ()
1204   "Fancy splitting method.
1205 See the documentation for the variable `nnmail-split-fancy' for documentation."
1206   (let ((syntab (syntax-table)))
1207     (unwind-protect
1208         (progn
1209           (set-syntax-table nnmail-split-fancy-syntax-table)
1210           (nnmail-split-it nnmail-split-fancy))
1211       (set-syntax-table syntab))))
1212
1213 (defvar nnmail-split-cache nil)
1214 ;; Alist of split expressions their equivalent regexps.
1215
1216 (defun nnmail-split-it (split)
1217   ;; Return a list of groups matching SPLIT.
1218   (let (cached-pair)
1219     (cond
1220      ;; nil split
1221      ((null split)
1222       nil)
1223
1224      ;; A group name.  Do the \& and \N subs into the string.
1225      ((stringp split)
1226       (when nnmail-split-tracing
1227         (push (format "\"%s\"" split) nnmail-split-trace))
1228       (list (nnmail-expand-newtext split)))
1229
1230      ;; Junk the message.
1231      ((eq split 'junk)
1232       (when nnmail-split-tracing
1233         (push "junk" nnmail-split-trace))
1234       (list 'junk))
1235
1236      ;; Builtin & operation.
1237      ((eq (car split) '&)
1238       (apply 'nconc (mapcar 'nnmail-split-it (cdr split))))
1239
1240      ;; Builtin | operation.
1241      ((eq (car split) '|)
1242       (let (done)
1243         (while (and (not done) (cdr split))
1244           (setq split (cdr split)
1245                 done (nnmail-split-it (car split))))
1246         done))
1247
1248      ;; Builtin : operation.
1249      ((eq (car split) ':)
1250       (nnmail-split-it (save-excursion (eval (cdr split)))))
1251
1252      ;; Check the cache for the regexp for this split.
1253      ((setq cached-pair (assq split nnmail-split-cache))
1254       (goto-char (point-max))
1255       ;; FIX FIX FIX problem with re-search-backward is that if you have
1256       ;; a split: (from "foo-\\(bar\\|baz\\)@gnus.org "mail.foo.\\1")
1257       ;; and someone mails a message with 'To: foo-bar@gnus.org' and
1258       ;; 'CC: foo-baz@gnus.org', we'll pick 'mail.foo.baz' as the group
1259       ;; if the cc line is a later header, even though the other choice
1260       ;; is probably better.  Also, this routine won't do a crosspost
1261       ;; when there are two different matches.
1262       ;; I guess you could just make this more determined, and it could
1263       ;; look for still more matches prior to this one, and recurse
1264       ;; on each of the multiple matches hit.  Of course, then you'd
1265       ;; want to make sure that nnmail-article-group or nnmail-split-fancy
1266       ;; removed duplicates, since there might be more of those.
1267       ;; I guess we could also remove duplicates in the & split case, since
1268       ;; that's the only thing that can introduce them.
1269       (when (re-search-backward (cdr cached-pair) nil t)
1270         (when nnmail-split-tracing
1271           (push (cdr cached-pair) nnmail-split-trace))
1272         ;; Someone might want to do a \N sub on this match, so get the
1273         ;; correct match positions.
1274         (goto-char (match-end 0))
1275         (let ((value (nth 1 split)))
1276           (re-search-backward (if (symbolp value)
1277                                   (cdr (assq value nnmail-split-abbrev-alist))
1278                                 value)
1279                               (match-end 1)))
1280         (nnmail-split-it (nth 2 split))))
1281
1282      ;; Not in cache, compute a regexp for the field/value pair.
1283      (t
1284       (let* ((field (nth 0 split))
1285              (value (nth 1 split))
1286              (regexp (concat "^\\(\\("
1287                              (if (symbolp field)
1288                                  (cdr (assq field nnmail-split-abbrev-alist))
1289                                field)
1290                              "\\):.*\\)\\<\\("
1291                              (if (symbolp value)
1292                                  (cdr (assq value nnmail-split-abbrev-alist))
1293                                value)
1294                              "\\)\\>")))
1295         (push (cons split regexp) nnmail-split-cache)
1296         ;; Now that it's in the cache, just call nnmail-split-it again
1297         ;; on the same split, which will find it immediately in the cache.
1298         (nnmail-split-it split))))))
1299
1300 (defun nnmail-expand-newtext (newtext)
1301   (let ((len (length newtext))
1302         (pos 0)
1303         c expanded beg N did-expand)
1304     (while (< pos len)
1305       (setq beg pos)
1306       (while (and (< pos len)
1307                   (not (= (aref newtext pos) ?\\)))
1308         (setq pos (1+ pos)))
1309       (unless (= beg pos)
1310         (push (substring newtext beg pos) expanded))
1311       (when (< pos len)
1312         ;; We hit a \; expand it.
1313         (setq did-expand t
1314               pos (1+ pos)
1315               c (aref newtext pos))
1316         (if (not (or (= c ?\&)
1317                      (and (>= c ?1)
1318                           (<= c ?9))))
1319             ;; \ followed by some character we don't expand.
1320             (push (char-to-string c) expanded)
1321           ;; \& or \N
1322           (if (= c ?\&)
1323               (setq N 0)
1324             (setq N (- c ?0)))
1325           (when (match-beginning N)
1326             (push (buffer-substring (match-beginning N) (match-end N))
1327                   expanded))))
1328       (setq pos (1+ pos)))
1329     (if did-expand
1330         (apply 'concat (nreverse expanded))
1331       newtext)))
1332
1333 ;; Get a list of spool files to read.
1334 (defun nnmail-get-spool-files (&optional group)
1335   (if (null nnmail-spool-file)
1336       ;; No spool file whatsoever.
1337       nil
1338     (let* ((procmails
1339             ;; If procmail is used to get incoming mail, the files
1340             ;; are stored in this directory.
1341             (and (file-exists-p nnmail-procmail-directory)
1342                  (or (eq nnmail-spool-file 'procmail)
1343                      nnmail-use-procmail)
1344                  (directory-files
1345                   nnmail-procmail-directory
1346                   t (concat (if group (concat "^" (regexp-quote group)) "")
1347                             nnmail-procmail-suffix "$"))))
1348            (p procmails)
1349            (crash (when (and (file-exists-p nnmail-crash-box)
1350                              (> (nnheader-file-size
1351                                  (file-truename nnmail-crash-box))
1352                                 0))
1353                     (list nnmail-crash-box))))
1354       ;; Remove any directories that inadvertently match the procmail
1355       ;; suffix, which might happen if the suffix is "".
1356       (while p
1357         (when (file-directory-p (car p))
1358           (setq procmails (delete (car p) procmails)))
1359         (setq p (cdr p)))
1360       ;; Return the list of spools.
1361       (append
1362        crash
1363        (cond ((and group
1364                    (or (eq nnmail-spool-file 'procmail)
1365                        nnmail-use-procmail)
1366                    procmails)
1367               procmails)
1368              ((and group
1369                    (eq nnmail-spool-file 'procmail))
1370               nil)
1371              ((listp nnmail-spool-file)
1372               (nconc
1373                (apply
1374                 'nconc
1375                 (mapcar
1376                  (lambda (file)
1377                    (if (and (not (string-match "^po:" file))
1378                             (file-directory-p file))
1379                        (nnheader-directory-regular-files file)
1380                      (list file)))
1381                  nnmail-spool-file))
1382                procmails))
1383              ((stringp nnmail-spool-file)
1384               (if (and (not (string-match "^po:" nnmail-spool-file))
1385                        (file-directory-p nnmail-spool-file))
1386                   (nconc
1387                    (nnheader-directory-regular-files nnmail-spool-file)
1388                    procmails)
1389                 (cons nnmail-spool-file procmails)))
1390              ((eq nnmail-spool-file 'pop)
1391               (cons (format "po:%s" (user-login-name)) procmails))
1392              (t
1393               procmails))))))
1394
1395 ;; Activate a backend only if it isn't already activated.
1396 ;; If FORCE, re-read the active file even if the backend is
1397 ;; already activated.
1398 (defun nnmail-activate (backend &optional force)
1399   (nnheader-init-server-buffer)
1400   (let (file timestamp file-time)
1401     (if (or (not (symbol-value (intern (format "%s-group-alist" backend))))
1402             force
1403             (and (setq file (ignore-errors
1404                               (symbol-value (intern (format "%s-active-file"
1405                                                             backend)))))
1406                  (setq file-time (nth 5 (file-attributes file)))
1407                  (or (not
1408                       (setq timestamp
1409                             (condition-case ()
1410                                 (symbol-value (intern
1411                                                (format "%s-active-timestamp"
1412                                                        backend)))
1413                               (error 'none))))
1414                      (not (consp timestamp))
1415                      (equal timestamp '(0 0))
1416                      (> (nth 0 file-time) (nth 0 timestamp))
1417                      (and (= (nth 0 file-time) (nth 0 timestamp))
1418                           (> (nth 1 file-time) (nth 1 timestamp))))))
1419         (save-excursion
1420           (or (eq timestamp 'none)
1421               (set (intern (format "%s-active-timestamp" backend))
1422                    file-time))
1423           (funcall (intern (format "%s-request-list" backend)))))
1424     t))
1425
1426 (defun nnmail-message-id ()
1427   (concat "<" (message-unique-id) "@totally-fudged-out-message-id>"))
1428
1429 ;;;
1430 ;;; nnmail duplicate handling
1431 ;;;
1432
1433 (defvar nnmail-cache-buffer nil)
1434
1435 (defun nnmail-cache-open ()
1436   (if (or (not nnmail-treat-duplicates)
1437           (and nnmail-cache-buffer
1438                (buffer-name nnmail-cache-buffer)))
1439       ()                                ; The buffer is open.
1440     (save-excursion
1441       (set-buffer
1442        (setq nnmail-cache-buffer
1443              (get-buffer-create " *nnmail message-id cache*")))
1444       (buffer-disable-undo (current-buffer))
1445       (when (file-exists-p nnmail-message-id-cache-file)
1446         (nnheader-insert-file-contents nnmail-message-id-cache-file))
1447       (set-buffer-modified-p nil)
1448       (current-buffer))))
1449
1450 (defun nnmail-cache-close ()
1451   (when (and nnmail-cache-buffer
1452              nnmail-treat-duplicates
1453              (buffer-name nnmail-cache-buffer)
1454              (buffer-modified-p nnmail-cache-buffer))
1455     (save-excursion
1456       (set-buffer nnmail-cache-buffer)
1457       ;; Weed out the excess number of Message-IDs.
1458       (goto-char (point-max))
1459       (when (search-backward "\n" nil t nnmail-message-id-cache-length)
1460         (progn
1461           (beginning-of-line)
1462           (delete-region (point-min) (point))))
1463       ;; Save the buffer.
1464       (or (file-exists-p (file-name-directory nnmail-message-id-cache-file))
1465           (make-directory (file-name-directory nnmail-message-id-cache-file)
1466                           t))
1467       (nnmail-write-region (point-min) (point-max)
1468                            nnmail-message-id-cache-file nil 'silent)
1469       (set-buffer-modified-p nil)
1470       (setq nnmail-cache-buffer nil)
1471       (kill-buffer (current-buffer)))))
1472
1473 (defun nnmail-cache-insert (id)
1474   (when nnmail-treat-duplicates
1475     (unless (gnus-buffer-live-p nnmail-cache-buffer)
1476       (nnmail-cache-open))
1477     (save-excursion
1478       (set-buffer nnmail-cache-buffer)
1479       (goto-char (point-max))
1480       (insert id "\n"))))
1481
1482 (defun nnmail-cache-id-exists-p (id)
1483   (when nnmail-treat-duplicates
1484     (save-excursion
1485       (set-buffer nnmail-cache-buffer)
1486       (goto-char (point-max))
1487       (search-backward id nil t))))
1488
1489 (defun nnmail-fetch-field (header)
1490   (save-excursion
1491     (save-restriction
1492       (message-narrow-to-head)
1493       (message-fetch-field header))))
1494
1495 (defun nnmail-check-duplication (message-id func artnum-func)
1496   (run-hooks 'nnmail-prepare-incoming-message-hook)
1497   ;; If this is a duplicate message, then we do not save it.
1498   (let* ((duplication (nnmail-cache-id-exists-p message-id))
1499          (case-fold-search t)
1500          (action (when duplication
1501                    (cond
1502                     ((memq nnmail-treat-duplicates '(warn delete))
1503                      nnmail-treat-duplicates)
1504                     ((nnheader-functionp nnmail-treat-duplicates)
1505                      (funcall nnmail-treat-duplicates message-id))
1506                     (t
1507                      nnmail-treat-duplicates))))
1508          group-art)
1509     ;; Let the backend save the article (or not).
1510     (cond
1511      ((not duplication)
1512       (nnmail-cache-insert message-id)
1513       (funcall func (setq group-art
1514                           (nreverse (nnmail-article-group artnum-func)))))
1515      ((eq action 'delete)
1516       (setq group-art nil))
1517      ((eq action 'warn)
1518       ;; We insert a warning.
1519       (let ((case-fold-search t))
1520         (goto-char (point-min))
1521         (re-search-forward "^message-id[ \t]*:" nil t)
1522         (beginning-of-line)
1523         (insert
1524          "Gnus-Warning: This is a duplicate of message " message-id "\n")
1525         (funcall func (setq group-art
1526                             (nreverse (nnmail-article-group artnum-func))))))
1527      (t
1528       (funcall func (setq group-art
1529                           (nreverse (nnmail-article-group artnum-func))))))
1530     ;; Add the group-art list to the history list.
1531     (if group-art
1532         (push group-art nnmail-split-history)
1533       (delete-region (point-min) (point-max)))))
1534
1535 ;;; Get new mail.
1536
1537 (defun nnmail-get-value (&rest args)
1538   (let ((sym (intern (apply 'format args))))
1539     (when (boundp sym)
1540       (symbol-value sym))))
1541
1542 (defun nnmail-get-new-mail (method exit-func temp
1543                                    &optional group spool-func)
1544   "Read new incoming mail."
1545   (let* ((spools (nnmail-get-spool-files group))
1546          (group-in group)
1547          nnmail-current-spool incoming incomings spool)
1548     (when (and (nnmail-get-value "%s-get-new-mail" method)
1549                nnmail-spool-file)
1550       ;; We first activate all the groups.
1551       (nnmail-activate method)
1552       ;; Allow the user to hook.
1553       (run-hooks 'nnmail-pre-get-new-mail-hook)
1554       ;; Open the message-id cache.
1555       (nnmail-cache-open)
1556       ;; The we go through all the existing spool files and split the
1557       ;; mail from each.
1558       (while spools
1559         (setq spool (pop spools))
1560         ;; We read each spool file if either the spool is a POP-mail
1561         ;; spool, or the file exists.  We can't check for the
1562         ;; existence of POPped mail.
1563         (when (or (string-match "^po:" spool)
1564                   (and (file-exists-p (file-truename spool))
1565                        (> (nnheader-file-size (file-truename spool)) 0)))
1566           (nnheader-message 3 "%s: Reading incoming mail..." method)
1567           (when (and (nnmail-move-inbox spool)
1568                      (file-exists-p nnmail-crash-box))
1569             (setq nnmail-current-spool spool)
1570             ;; There is new mail.  We first find out if all this mail
1571             ;; is supposed to go to some specific group.
1572             (setq group (nnmail-get-split-group spool group-in))
1573             ;; We split the mail
1574             (nnmail-split-incoming
1575              nnmail-crash-box (intern (format "%s-save-mail" method))
1576              spool-func group (intern (format "%s-active-number" method)))
1577             ;; Check whether the inbox is to be moved to the special tmp dir.
1578             (setq incoming
1579                   (nnmail-make-complex-temp-name
1580                    (expand-file-name
1581                     (if nnmail-tmp-directory
1582                         (concat
1583                          (file-name-as-directory nnmail-tmp-directory)
1584                          (file-name-nondirectory
1585                           (concat (file-name-as-directory temp) "Incoming")))
1586                       (concat (file-name-as-directory temp) "Incoming")))))
1587             (unless (file-exists-p (file-name-directory incoming))
1588               (make-directory (file-name-directory incoming) t))
1589             (rename-file nnmail-crash-box incoming t)
1590             (push incoming incomings))))
1591       ;; If we did indeed read any incoming spools, we save all info.
1592       (when incomings
1593         (nnmail-save-active
1594          (nnmail-get-value "%s-group-alist" method)
1595          (nnmail-get-value "%s-active-file" method))
1596         (when exit-func
1597           (funcall exit-func))
1598         (run-hooks 'nnmail-read-incoming-hook)
1599         (nnheader-message 3 "%s: Reading incoming mail...done" method))
1600       ;; Close the message-id cache.
1601       (nnmail-cache-close)
1602       ;; Allow the user to hook.
1603       (run-hooks 'nnmail-post-get-new-mail-hook)
1604       ;; Delete all the temporary files.
1605       (while incomings
1606         (setq incoming (pop incomings))
1607         (and nnmail-delete-incoming
1608              (file-exists-p incoming)
1609              (file-writable-p incoming)
1610              (delete-file incoming))))))
1611
1612 (defun nnmail-expired-article-p (group time force &optional inhibit)
1613   "Say whether an article that is TIME old in GROUP should be expired."
1614   (if force
1615       t
1616     (let ((days (or (and nnmail-expiry-wait-function
1617                          (funcall nnmail-expiry-wait-function group))
1618                     nnmail-expiry-wait)))
1619       (cond ((or (eq days 'never)
1620                  (and (not force)
1621                       inhibit))
1622              ;; This isn't an expirable group.
1623              nil)
1624             ((eq days 'immediate)
1625              ;; We expire all articles on sight.
1626              t)
1627             ((equal time '(0 0))
1628              ;; This is an ange-ftp group, and we don't have any dates.
1629              nil)
1630             ((numberp days)
1631              (setq days (days-to-time days))
1632              ;; Compare the time with the current time.
1633              (time-less-p days (time-since time)))))))
1634
1635 (defvar nnmail-read-passwd nil)
1636 (defun nnmail-read-passwd (prompt &rest args)
1637   "Read a password using PROMPT.
1638 If ARGS, PROMPT is used as an argument to `format'."
1639   (let ((prompt
1640          (if args
1641              (apply 'format prompt args)
1642            prompt)))
1643     (unless nnmail-read-passwd
1644       (if (load "passwd" t)
1645           (setq nnmail-read-passwd 'read-passwd)
1646         (unless (fboundp 'ange-ftp-read-passwd)
1647           (autoload 'ange-ftp-read-passwd "ange-ftp"))
1648         (setq nnmail-read-passwd 'ange-ftp-read-passwd)))
1649     (funcall nnmail-read-passwd prompt)))
1650
1651 (defun nnmail-check-syntax ()
1652   "Check (and modify) the syntax of the message in the current buffer."
1653   (save-restriction
1654     (message-narrow-to-head)
1655     (let ((case-fold-search t))
1656       (unless (re-search-forward "^Message-ID[ \t]*:" nil t)
1657         (insert "Message-ID: " (nnmail-message-id) "\n")))))
1658
1659 (defun nnmail-write-region (start end filename &optional append visit lockname)
1660   "Do a `write-region', and then set the file modes."
1661   (let ((coding-system-for-write nnmail-file-coding-system)
1662         (pathname-coding-system 'binary))
1663     (write-region start end filename append visit lockname)
1664     (set-file-modes filename nnmail-default-file-modes)))
1665
1666 ;;;
1667 ;;; Status functions
1668 ;;;
1669
1670 (defun nnmail-replace-status (name value)
1671   "Make status NAME and VALUE part of the current status line."
1672   (save-restriction
1673     (message-narrow-to-head)
1674     (let ((status (nnmail-decode-status)))
1675       (setq status (delq (member name status) status))
1676       (when value
1677         (push (cons name value) status))
1678       (message-remove-header "status")
1679       (goto-char (point-max))
1680       (insert "Status: " (nnmail-encode-status status) "\n"))))
1681
1682 (defun nnmail-decode-status ()
1683   "Return a status-value alist from STATUS."
1684   (goto-char (point-min))
1685   (when (re-search-forward "^Status: " nil t)
1686     (let (name value status)
1687       (save-restriction
1688         ;; Narrow to the status.
1689         (narrow-to-region
1690          (point)
1691          (if (re-search-forward "^[^ \t]" nil t)
1692              (1- (point))
1693            (point-max)))
1694         ;; Go through all elements and add them to the list.
1695         (goto-char (point-min))
1696         (while (re-search-forward "[^ \t=]+" nil t)
1697           (setq name (match-string 0))
1698           (if (not (= (following-char) ?=))
1699               ;; Implied "yes".
1700               (setq value "yes")
1701             (forward-char 1)
1702             (if (not (= (following-char) ?\"))
1703                 (if (not (looking-at "[^ \t]"))
1704                     ;; Implied "no".
1705                     (setq value "no")
1706                   ;; Unquoted value.
1707                   (setq value (match-string 0))
1708                   (goto-char (match-end 0)))
1709               ;; Quoted value.
1710               (setq value (read (current-buffer)))))
1711           (push (cons name value) status)))
1712       status)))
1713
1714 (defun nnmail-encode-status (status)
1715   "Return a status string from STATUS."
1716   (mapconcat
1717    (lambda (elem)
1718      (concat
1719       (car elem) "="
1720       (if (string-match "[ \t]" (cdr elem))
1721           (prin1-to-string (cdr elem))
1722         (cdr elem))))
1723    status " "))
1724
1725 (defun nnmail-split-history ()
1726   "Generate an overview of where the last mail split put articles."
1727   (interactive)
1728   (unless nnmail-split-history
1729     (error "No current split history"))
1730   (with-output-to-temp-buffer "*nnmail split history*"
1731     (let ((history nnmail-split-history)
1732           elem)
1733       (while (setq elem (pop history))
1734         (princ (mapconcat (lambda (ga)
1735                             (concat (car ga) ":" (int-to-string (cdr ga))))
1736                           elem
1737                           ", "))
1738         (princ "\n")))))
1739
1740 (defun nnmail-purge-split-history (group)
1741   "Remove all instances of GROUP from `nnmail-split-history'."
1742   (let ((history nnmail-split-history))
1743     (while history
1744       (setcar history (gnus-delete-if (lambda (e) (string= (car e) group))
1745                                       (car history)))
1746       (pop history))
1747     (setq nnmail-split-history (delq nil nnmail-split-history))))
1748
1749 (defun nnmail-new-mail-p (group)
1750   "Say whether GROUP has new mail."
1751   (let ((his nnmail-split-history)
1752         found)
1753     (while his
1754       (when (assoc group (pop his))
1755         (setq found t
1756               his nil)))
1757     found))
1758
1759 (eval-and-compile
1760   (autoload 'pop3-movemail "pop3"))
1761
1762 (defun nnmail-pop3-movemail (inbox crashbox)
1763   "Function to move mail from INBOX on a pop3 server to file CRASHBOX."
1764   (let ((pop3-maildrop
1765          (substring inbox (match-end (string-match "^po:" inbox)))))
1766     (pop3-movemail crashbox)))
1767
1768 (defun nnmail-within-headers-p ()
1769   "Check to see if point is within the headers of a unix mail message.
1770 Doesn't change point."
1771   (let ((pos (point)))
1772     (save-excursion
1773       (and (nnmail-search-unix-mail-delim-backward)
1774            (not (search-forward "\n\n" pos t))))))
1775
1776 (run-hooks 'nnmail-load-hook)
1777
1778 (provide 'nnmail)
1779
1780 ;;; nnmail.el ends here