Importing pgnus-0.16
[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 'timezone)
32 (require 'message)
33 (require 'custom)
34 (require 'gnus-util)
35
36 (eval-and-compile
37   (autoload 'gnus-error "gnus-util")
38   (autoload 'gnus-buffer-live-p "gnus-util"))
39
40 (defgroup nnmail nil
41   "Reading mail with Gnus."
42   :group 'gnus)
43
44 (defgroup nnmail-retrieve nil
45   "Retrieving new mail."
46   :group 'nnmail)
47
48 (defgroup nnmail-prepare nil
49   "Preparing (or mangling) new mail after retrival."
50   :group 'nnmail)
51
52 (defgroup nnmail-duplicate nil
53   "Handling of duplicate mail messages."
54   :group 'nnmail)
55
56 (defgroup nnmail-split nil
57   "Organizing the incomming mail in folders."
58   :group 'nnmail)
59
60 (defgroup nnmail-files nil
61   "Mail files."
62   :group 'gnus-files
63   :group 'nnmail)
64
65 (defgroup nnmail-expire nil
66   "Expiring old mail."
67   :group 'nnmail)
68
69 (defgroup nnmail-procmail nil
70   "Interfacing with procmail and other mail agents."
71   :group 'nnmail)
72
73 (defgroup nnmail-various nil
74   "Various mail options."
75   :group 'nnmail)
76
77 (defcustom nnmail-split-methods
78   '(("mail.misc" ""))
79   "*Incoming mail will be split according to this variable.
80
81 If you'd like, for instance, one mail group for mail from the
82 \"4ad-l\" mailing list, one group for junk mail and one for everything
83 else, you could do something like this:
84
85  (setq nnmail-split-methods
86        '((\"mail.4ad\" \"From:.*4ad\")
87          (\"mail.junk\" \"From:.*Lars\\\\|Subject:.*buy\")
88          (\"mail.misc\" \"\")))
89
90 As you can see, this variable is a list of lists, where the first
91 element in each \"rule\" is the name of the group (which, by the way,
92 does not have to be called anything beginning with \"mail\",
93 \"yonka.zow\" is a fine, fine name), and the second is a regexp that
94 nnmail will try to match on the header to find a fit.
95
96 The second element can also be a function.  In that case, it will be
97 called narrowed to the headers with the first element of the rule as
98 the argument.  It should return a non-nil value if it thinks that the
99 mail belongs in that group.
100
101 The last element should always have \"\" as the regexp.
102
103 This variable can also have a function as its value."
104   :group 'nnmail-split
105   :type '(choice (repeat :tag "Alist" (group (string :tag "Name") regexp))
106                  (function-item nnmail-split-fancy)
107                  (function :tag "Other")))
108
109 ;; Suggested by Erik Selberg <speed@cs.washington.edu>.
110 (defcustom nnmail-crosspost t
111   "If non-nil, do crossposting if several split methods match the mail.
112 If nil, the first match found will be used."
113   :group 'nnmail-split
114   :type 'boolean)
115
116 ;; Added by gord@enci.ucalgary.ca (Gordon Matzigkeit).
117 (defcustom nnmail-keep-last-article nil
118   "If non-nil, nnmail will never delete/move a group's last article.
119 It can be marked expirable, so it will be deleted when it is no longer last.
120
121 You may need to set this variable if other programs are putting
122 new mail into folder numbers that Gnus has marked as expired."
123   :group 'nnmail-procmail
124   :group 'nnmail-various
125   :type 'boolean)
126
127 (defcustom nnmail-use-long-file-names nil
128   "If non-nil the mail backends will use long file and directory names.
129 If nil, groups like \"mail.misc\" will end up in directories like
130 \"mail/misc/\"."
131   :group 'nnmail-files
132   :type 'boolean)
133
134 (defcustom nnmail-default-file-modes 384
135   "Set the mode bits of all new mail files to this integer."
136   :group 'nnmail-files
137   :type 'integer)
138
139 (defcustom nnmail-expiry-wait 7
140   "*Expirable articles that are older than this will be expired.
141 This variable can either be a number (which will be interpreted as a
142 number of days) -- this doesn't have to be an integer.  This variable
143 can also be `immediate' and `never'."
144   :group 'nnmail-expire
145   :type '(choice (const immediate)
146                  (integer :tag "days")
147                  (const never)))
148
149 (defcustom nnmail-expiry-wait-function nil
150   "Variable that holds function to specify how old articles should be before they are expired.
151   The function will be called with the name of the group that the
152 expiry is to be performed in, and it should return an integer that
153 says how many days an article can be stored before it is considered
154 \"old\".  It can also return the values `never' and `immediate'.
155
156 Eg.:
157
158 \(setq nnmail-expiry-wait-function
159       (lambda (newsgroup)
160         (cond ((string-match \"private\" newsgroup) 31)
161               ((string-match \"junk\" newsgroup) 1)
162               ((string-match \"important\" newsgroup) 'never)
163               (t 7))))"
164   :group 'nnmail-expire
165   :type '(choice (const :tag "nnmail-expiry-wait" nil)
166                  (function :format "%v" nnmail-)))
167
168 (defcustom nnmail-cache-accepted-message-ids nil
169   "If non-nil, put Message-IDs of Gcc'd articles into the duplicate cache."
170   :group 'nnmail
171   :type 'boolean)
172
173 (defcustom nnmail-spool-file
174   (or (getenv "MAIL")
175       (concat "/usr/spool/mail/" (user-login-name)))
176   "*Where the mail backends will look for incoming mail.
177 This variable is \"/usr/spool/mail/$user\" by default.
178 If this variable is nil, no mail backends will read incoming mail.
179 If this variable is a list, all files mentioned in this list will be
180 used as incoming mailboxes.
181 If this variable is a directory (i. e., it's name ends with a \"/\"),
182 treat all files in that directory as incoming spool files."
183   :group 'nnmail-files
184   :type '(choice (file :tag "File")
185                  (repeat :tag "Files" file)))
186
187 (defcustom nnmail-crash-box "~/.gnus-crash-box"
188   "File where Gnus will store mail while processing it."
189   :group 'nnmail-files
190   :type 'file)
191
192 (defcustom nnmail-use-procmail nil
193   "*If non-nil, the mail backends will look in `nnmail-procmail-directory' for spool files.
194 The file(s) in `nnmail-spool-file' will also be read."
195   :group 'nnmail-procmail
196   :type 'boolean)
197
198 (defcustom nnmail-procmail-directory "~/incoming/"
199   "*When using procmail (and the like), incoming mail is put in this directory.
200 The Gnus mail backends will read the mail from this directory."
201   :group 'nnmail-procmail
202   :type 'directory)
203
204 (defcustom nnmail-procmail-suffix "\\.spool"
205   "*Suffix of files created by procmail (and the like).
206 This variable might be a suffix-regexp to match the suffixes of
207 several files - eg. \".spool[0-9]*\"."
208   :group 'nnmail-procmail
209   :type 'regexp)
210
211 (defcustom nnmail-resplit-incoming nil
212   "*If non-nil, re-split incoming procmail sorted mail."
213   :group 'nnmail-procmail
214   :type 'boolean)
215
216 (defcustom nnmail-delete-file-function 'delete-file
217   "Function called to delete files in some mail backends."
218   :group 'nnmail-files
219   :type 'function)
220
221 (defcustom nnmail-crosspost-link-function
222   (if (string-match "windows-nt\\|emx" (symbol-name system-type))
223       'copy-file
224     'add-name-to-file)
225   "*Function called to create a copy of a file.
226 This is `add-name-to-file' by default, which means that crossposts
227 will use hard links.  If your file system doesn't allow hard
228 links, you could set this variable to `copy-file' instead."
229   :group 'nnmail-files
230   :type '(radio (function-item add-name-to-file)
231                 (function-item copy-file)
232                 (function :tag "Other")))
233
234 (defcustom nnmail-movemail-program "movemail"
235   "*A command to be executed to move mail from the inbox.
236 The default is \"movemail\".
237
238 This can also be a function.  In that case, the function will be
239 called with two parameters -- the name of the INBOX file, and the file
240 to be moved to."
241   :group 'nnmail-files
242   :group 'nnmail-retrieve
243   :type 'string)
244
245 (defcustom nnmail-pop-password-required nil
246   "*Non-nil if a password is required when reading mail using POP."
247   :group 'nnmail-retrieve
248   :type 'boolean)
249
250 (defcustom nnmail-read-incoming-hook
251   (if (eq system-type 'windows-nt)
252       '(nnheader-ms-strip-cr)
253     nil)
254   "*Hook that will be run after the incoming mail has been transferred.
255 The incoming mail is moved from `nnmail-spool-file' (which normally is
256 something like \"/usr/spool/mail/$user\") to the user's home
257 directory.  This hook is called after the incoming mail box has been
258 emptied, and can be used to call any mail box programs you have
259 running (\"xwatch\", etc.)
260
261 Eg.
262
263 \(add-hook 'nnmail-read-incoming-hook
264            (lambda ()
265              (start-process \"mailsend\" nil
266                             \"/local/bin/mailsend\" \"read\" \"mbox\")))
267
268 If you have xwatch running, this will alert it that mail has been
269 read.
270
271 If you use `display-time', you could use something like this:
272
273 \(add-hook 'nnmail-read-incoming-hook
274           (lambda ()
275             ;; Update the displayed time, since that will clear out
276             ;; the flag that says you have mail.
277             (when (eq (process-status \"display-time\") 'run)
278               (display-time-filter display-time-process \"\"))))"
279   :group 'nnmail-prepare
280   :type 'hook)
281
282 ;; Suggested by Erik Selberg <speed@cs.washington.edu>.
283 (defcustom nnmail-prepare-incoming-hook nil
284   "Hook called before treating incoming mail.
285 The hook is run in a buffer with all the new, incoming mail."
286   :group 'nnmail-prepare
287   :type 'hook)
288
289 (defcustom nnmail-prepare-incoming-header-hook nil
290   "Hook called narrowed to the headers of each message.
291 This can be used to remove excessive spaces (and stuff like
292 that) from the headers before splitting and saving the messages."
293   :group 'nnmail-prepare
294   :type 'hook)
295
296 (defcustom nnmail-prepare-incoming-message-hook nil
297   "Hook called narrowed to each message."
298   :group 'nnmail-prepare
299   :type 'hook)
300
301 (defcustom nnmail-list-identifiers nil
302   "Regexp that matches list identifiers to be removed.
303 This can also be a list of regexps."
304   :group 'nnmail-prepare
305   :type '(choice (const :tag "none" nil)
306                  (regexp :value ".*")
307                  (repeat :value (".*") regexp)))
308
309 (defcustom nnmail-pre-get-new-mail-hook nil
310   "Hook called just before starting to handle new incoming mail."
311   :group 'nnmail-retrieve
312   :type 'hook)
313
314 (defcustom nnmail-post-get-new-mail-hook nil
315   "Hook called just after finishing handling new incoming mail."
316   :group 'nnmail-retrieve
317   :type 'hook)
318
319 (defcustom nnmail-split-hook nil
320   "Hook called before deciding where to split an article.
321 The functions in this hook are free to modify the buffer
322 contents in any way they choose -- the buffer contents are
323 discarded after running the split process."
324   :group 'nnmail-split
325   :type 'hook)
326
327 ;; Suggested by Mejia Pablo J <pjm9806@usl.edu>.
328 (defcustom nnmail-tmp-directory nil
329   "*If non-nil, use this directory for temporary storage.
330 Used when reading incoming mail."
331   :group 'nnmail-files
332   :group 'nnmail-retrieve
333   :type '(choice (const :tag "default" nil)
334                  (directory :format "%v")))
335
336 (defcustom nnmail-large-newsgroup 50
337   "*The number of the articles which indicates a large newsgroup.
338 If the number of the articles is greater than the value, verbose
339 messages will be shown to indicate the current status."
340   :group 'nnmail-various
341   :type 'integer)
342
343 (defcustom nnmail-split-fancy "mail.misc"
344   "Incoming mail can be split according to this fancy variable.
345 To enable this, set `nnmail-split-methods' to `nnmail-split-fancy'.
346
347 The format of this variable is SPLIT, where SPLIT can be one of
348 the following:
349
350 GROUP: Mail will be stored in GROUP (a string).
351
352 \(FIELD VALUE SPLIT): If the message field FIELD (a regexp) contains
353   VALUE (a regexp), store the messages as specified by SPLIT.
354
355 \(| SPLIT...): Process each SPLIT expression until one of them matches.
356   A SPLIT expression is said to match if it will cause the mail
357   message to be stored in one or more groups.
358
359 \(& SPLIT...): Process each SPLIT expression.
360
361 \(: FUNCTION optional args): Call FUNCTION with the optional args, in
362   the buffer containing the message headers.  The return value FUNCTION
363   should be a split, which is then recursively processed.
364
365 FIELD must match a complete field name.  VALUE must match a complete
366 word according to the `nnmail-split-fancy-syntax-table' syntax table.
367 You can use \".*\" in the regexps to match partial field names or words.
368
369 FIELD and VALUE can also be lisp symbols, in that case they are expanded
370 as specified in `nnmail-split-abbrev-alist'.
371
372 GROUP can contain \\& and \\N which will substitute from matching
373 \\(\\) patterns in the previous VALUE.
374
375 Example:
376
377 \(setq nnmail-split-methods 'nnmail-split-fancy
378       nnmail-split-fancy
379       ;; Messages from the mailer daemon are not crossposted to any of
380       ;; the ordinary groups.  Warnings are put in a separate group
381       ;; from real errors.
382       '(| (\"from\" mail (| (\"subject\" \"warn.*\" \"mail.warning\")
383                           \"mail.misc\"))
384           ;; Non-error messages are crossposted to all relevant
385           ;; groups, but we don't crosspost between the group for the
386           ;; (ding) list and the group for other (ding) related mail.
387           (& (| (any \"ding@ifi\\\\.uio\\\\.no\" \"ding.list\")
388                 (\"subject\" \"ding\" \"ding.misc\"))
389              ;; Other mailing lists...
390              (any \"procmail@informatik\\\\.rwth-aachen\\\\.de\" \"procmail.list\")
391              (any \"SmartList@informatik\\\\.rwth-aachen\\\\.de\" \"SmartList.list\")
392              ;; People...
393              (any \"larsi@ifi\\\\.uio\\\\.no\" \"people.Lars Magne Ingebrigtsen\"))
394           ;; Unmatched mail goes to the catch all group.
395           \"misc.misc\"))"
396   :group 'nnmail-split
397   ;; Sigh!
398   :type 'sexp)
399
400 (defcustom nnmail-split-abbrev-alist
401   '((any . "from\\|to\\|cc\\|sender\\|apparently-to\\|resent-from\\|resent-to\\|resent-cc")
402     (mail . "mailer-daemon\\|postmaster\\|uucp")
403     (to . "to\\|cc\\|apparently-to\\|resent-to\\|resent-cc")
404     (from . "from\\|sender\\|resent-from")
405     (nato . "to\\|cc\\|resent-to\\|resent-cc")
406     (naany . "from\\|to\\|cc\\|sender\\|resent-from\\|resent-to\\|resent-cc"))
407   "*Alist of abbreviations allowed in `nnmail-split-fancy'."
408   :group 'nnmail-split
409   :type '(repeat (cons :format "%v" symbol regexp)))
410
411 (defcustom nnmail-delete-incoming nil
412   "*If non-nil, the mail backends will delete incoming files after
413 splitting."
414   :group 'nnmail-retrieve
415   :type 'boolean)
416
417 (defcustom nnmail-message-id-cache-length 1000
418   "*The approximate number of Message-IDs nnmail will keep in its cache.
419 If this variable is nil, no checking on duplicate messages will be
420 performed."
421   :group 'nnmail-duplicate
422   :type '(choice (const :tag "disable" nil)
423                  (integer :format "%v")))
424
425 (defcustom nnmail-message-id-cache-file "~/.nnmail-cache"
426   "*The file name of the nnmail Message-ID cache."
427   :group 'nnmail-duplicate
428   :group 'nnmail-files
429   :type 'file)
430
431 (defcustom nnmail-treat-duplicates 'warn
432   "*If non-nil, nnmail keep a cache of Message-IDs to discover mail duplicates.
433 Three values are legal: nil, which means that nnmail is not to keep a
434 Message-ID cache; `warn', which means that nnmail should insert extra
435 headers to warn the user about the duplication (this is the default);
436 and `delete', which means that nnmail will delete duplicated mails.
437
438 This variable can also be a function.  It will be called from a buffer
439 narrowed to the article in question with the Message-ID as a
440 parameter.  It should return nil, `warn' or `delete'."
441   :group 'nnmail-duplicate
442   :type '(choice (const :tag "off" nil)
443                  (const warn)
444                  (const delete)))
445
446 ;;; Internal variables.
447
448 (defvar nnmail-split-history nil
449   "List of group/article elements that say where the previous split put messages.")
450
451 (defvar nnmail-current-spool nil)
452
453 (defvar nnmail-pop-password nil
454   "*Password to use when reading mail from a POP server, if required.")
455
456 (defvar nnmail-split-fancy-syntax-table nil
457   "Syntax table used by `nnmail-split-fancy'.")
458 (unless (syntax-table-p nnmail-split-fancy-syntax-table)
459   (setq nnmail-split-fancy-syntax-table
460         (copy-syntax-table (standard-syntax-table)))
461   ;; support the %-hack
462   (modify-syntax-entry ?\% "." nnmail-split-fancy-syntax-table))
463
464 (defvar nnmail-prepare-save-mail-hook nil
465   "Hook called before saving mail.")
466
467 (defvar nnmail-moved-inboxes nil
468   "List of inboxes that have been moved.")
469
470 (defvar nnmail-internal-password nil)
471
472 (defvar nnmail-split-tracing nil)
473 (defvar nnmail-split-trace nil)
474
475 \f
476
477 (defconst nnmail-version "nnmail 1.0"
478   "nnmail version.")
479
480 \f
481
482 (defun nnmail-request-post (&optional server)
483   (mail-send-and-exit nil))
484
485 (defvar nnmail-file-coding-system 'binary
486   "Coding system used in nnmail.")
487
488 (defun nnmail-find-file (file)
489   "Insert FILE in server buffer safely."
490   (set-buffer nntp-server-buffer)
491   (erase-buffer)
492   (let ((format-alist nil)
493         (after-insert-file-functions nil))
494     (condition-case ()
495         (let ((coding-system-for-read nnmail-file-coding-system)
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                (nnheader-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       (buffer-disable-undo (current-buffer))
991       (erase-buffer)
992       (nnheader-insert-file-contents incoming)
993       (unless (zerop (buffer-size))
994         (goto-char (point-min))
995         (save-excursion (run-hooks 'nnmail-prepare-incoming-hook))
996         ;; Handle both babyl, MMDF and unix mail formats, since movemail will
997         ;; use the former when fetching from a mailbox, the latter when
998         ;; fetching from a file.
999         (cond ((or (looking-at "\^L")
1000                    (looking-at "BABYL OPTIONS:"))
1001                (nnmail-process-babyl-mail-format func artnum-func))
1002               ((looking-at "\^A\^A\^A\^A")
1003                (nnmail-process-mmdf-mail-format func artnum-func))
1004               (t
1005                (nnmail-process-unix-mail-format func artnum-func))))
1006       (when exit-func
1007         (funcall exit-func))
1008       (kill-buffer (current-buffer)))))
1009
1010 (defun nnmail-article-group (func &optional trace)
1011   "Look at the headers and return an alist of groups that match.
1012 FUNC will be called with the group name to determine the article number."
1013   (let ((methods nnmail-split-methods)
1014         (obuf (current-buffer))
1015         (beg (point-min))
1016         end group-art method regrepp)
1017     (if (and (sequencep methods)
1018              (= (length methods) 1))
1019         ;; If there is only just one group to put everything in, we
1020         ;; just return a list with just this one method in.
1021         (setq group-art
1022               (list (cons (caar methods) (funcall func (caar methods)))))
1023       ;; We do actual comparison.
1024       (save-excursion
1025         ;; Find headers.
1026         (goto-char beg)
1027         (setq end (if (search-forward "\n\n" nil t) (point) (point-max)))
1028         (set-buffer nntp-server-buffer)
1029         (erase-buffer)
1030         ;; Copy the headers into the work buffer.
1031         (insert-buffer-substring obuf beg end)
1032         ;; Fold continuation lines.
1033         (goto-char (point-min))
1034         (while (re-search-forward "\\(\r?\n[ \t]+\\)+" nil t)
1035           (replace-match " " t t))
1036         ;; Nuke pathologically long headers.  Since Gnus applies
1037         ;; pathologically complex regexps to the buffer, lines
1038         ;; that are looong will take longer than the Universe's
1039         ;; existence to process.
1040         (goto-char (point-min))
1041         (while (not (eobp))
1042           (end-of-line)
1043           (if (> (current-column) 1024)
1044               (gnus-delete-line)
1045             (forward-line 1)))
1046         ;; Allow washing.
1047         (goto-char (point-min))
1048         (run-hooks 'nnmail-split-hook)
1049         (when (setq nnmail-split-tracing trace)
1050           (setq nnmail-split-trace nil))
1051         (if (and (symbolp nnmail-split-methods)
1052                  (fboundp nnmail-split-methods))
1053             (let ((split
1054                    (condition-case nil
1055                        ;; `nnmail-split-methods' is a function, so we
1056                        ;; just call this function here and use the
1057                        ;; result.
1058                        (or (funcall nnmail-split-methods)
1059                            '("bogus"))
1060                      (error
1061                       (nnheader-message 5
1062                        "Error in `nnmail-split-methods'; using `bogus' mail group")
1063                       (sit-for 1)
1064                       '("bogus")))))
1065               (setq split (gnus-remove-duplicates split))
1066               ;; The article may be "cross-posted" to `junk'.  What
1067               ;; to do?  Just remove the `junk' spec.  Don't really
1068               ;; see anything else to do...
1069               (let (elem)
1070                 (while (setq elem (car (memq 'junk split)))
1071                   (setq split (delq elem split))))
1072               (when split
1073                 (setq group-art
1074                       (mapcar
1075                        (lambda (group) (cons group (funcall func group)))
1076                        split))))
1077           ;; Go through the split methods to find a match.
1078           (while (and methods
1079                       (or nnmail-crosspost
1080                           (not group-art)))
1081             (goto-char (point-max))
1082             (setq method (pop methods)
1083                   regrepp nil)
1084             (if (or methods
1085                     (not (equal "" (nth 1 method))))
1086                 (when (and
1087                        (ignore-errors
1088                          (if (stringp (nth 1 method))
1089                              (progn
1090                                (setq regrepp
1091                                      (string-match "\\\\[0-9&]" (car method)))
1092                                (re-search-backward (cadr method) nil t))
1093                            ;; Function to say whether this is a match.
1094                            (funcall (nth 1 method) (car method))))
1095                        ;; Don't enter the article into the same
1096                        ;; group twice.
1097                        (not (assoc (car method) group-art)))
1098                   (push (cons (if regrepp
1099                                   (replace-match
1100                                    (car method) nil nil (car method))
1101                                 (car method))
1102                               (funcall func (car method)))
1103                         group-art))
1104               ;; This is the final group, which is used as a
1105               ;; catch-all.
1106               (unless group-art
1107                 (setq group-art
1108                       (list (cons (car method)
1109                                   (funcall func (car method)))))))))
1110         ;; Produce a trace if non-empty.
1111         (when (and trace nnmail-split-trace)
1112           (let ((trace (nreverse nnmail-split-trace))
1113                 (restore (current-buffer)))
1114             (nnheader-set-temp-buffer "*Split Trace*")
1115             (gnus-add-buffer)
1116             (while trace
1117               (insert (car trace) "\n")
1118               (setq trace (cdr trace)))
1119             (goto-char (point-min))
1120             (gnus-configure-windows 'split-trace)
1121             (set-buffer restore)))
1122         ;; See whether the split methods returned `junk'.
1123         (if (equal group-art '(junk))
1124             nil
1125           ;; The article may be "cross-posted" to `junk'.  What
1126           ;; to do?  Just remove the `junk' spec.  Don't really
1127           ;; see anything else to do...
1128           (let (elem)
1129             (while (setq elem (car (memq 'junk group-art)))
1130               (setq group-art (delq elem group-art)))
1131             (nreverse group-art)))))))
1132
1133 (defun nnmail-insert-lines ()
1134   "Insert how many lines there are in the body of the mail.
1135 Return the number of characters in the body."
1136   (let (lines chars)
1137     (save-excursion
1138       (goto-char (point-min))
1139       (when (search-forward "\n\n" nil t)
1140         (setq chars (- (point-max) (point)))
1141         (setq lines (count-lines (point) (point-max)))
1142         (forward-char -1)
1143         (save-excursion
1144           (when (re-search-backward "^Lines: " nil t)
1145             (delete-region (point) (progn (forward-line 1) (point)))))
1146         (beginning-of-line)
1147         (insert (format "Lines: %d\n" (max lines 0)))
1148         chars))))
1149
1150 (defun nnmail-insert-xref (group-alist)
1151   "Insert an Xref line based on the (group . article) alist."
1152   (save-excursion
1153     (goto-char (point-min))
1154     (when (search-forward "\n\n" nil t)
1155       (forward-char -1)
1156       (when (re-search-backward "^Xref: " nil t)
1157         (delete-region (match-beginning 0)
1158                        (progn (forward-line 1) (point))))
1159       (insert (format "Xref: %s" (system-name)))
1160       (while group-alist
1161         (insert (format " %s:%d"
1162                         (nnheader-encode-coding-string
1163                          (caar group-alist)
1164                          nnmail-pathname-coding-system)
1165                         (cdar group-alist)))
1166         (setq group-alist (cdr group-alist)))
1167       (insert "\n"))))
1168
1169 ;;; Message washing functions
1170
1171 (defun nnmail-remove-leading-whitespace ()
1172   "Remove excessive whitespace from all headers."
1173   (goto-char (point-min))
1174   (while (re-search-forward "^\\([^ :]+: \\) +" nil t)
1175     (replace-match "\\1" t)))
1176
1177 (defun nnmail-remove-list-identifiers ()
1178   "Remove list identifiers from Subject headers."
1179   (let ((regexp (if (stringp nnmail-list-identifiers) nnmail-list-identifiers
1180                   (mapconcat 'identity nnmail-list-identifiers "\\|"))))
1181     (when regexp
1182       (goto-char (point-min))
1183       (when (re-search-forward
1184              (concat "^Subject: +\\(Re: +\\)?\\(" regexp "\\) *")
1185              nil t)
1186         (delete-region (match-beginning 2) (match-end 0))))))
1187
1188 (defun nnmail-remove-tabs ()
1189   "Translate TAB characters into SPACE characters."
1190   (subst-char-in-region (point-min) (point-max) ?\t ?  t))
1191
1192 ;;; Utility functions
1193
1194 (defun nnmail-make-complex-temp-name (prefix)
1195   (let ((newname (make-temp-name prefix))
1196         (newprefix prefix))
1197     (while (file-exists-p newname)
1198       (setq newprefix (concat newprefix "x"))
1199       (setq newname (make-temp-name newprefix)))
1200     newname))
1201
1202 ;; Written by Per Abrahamsen <amanda@iesd.auc.dk>.
1203
1204 (defun nnmail-split-fancy ()
1205   "Fancy splitting method.
1206 See the documentation for the variable `nnmail-split-fancy' for documentation."
1207   (let ((syntab (syntax-table)))
1208     (unwind-protect
1209         (progn
1210           (set-syntax-table nnmail-split-fancy-syntax-table)
1211           (nnmail-split-it nnmail-split-fancy))
1212       (set-syntax-table syntab))))
1213
1214 (defvar nnmail-split-cache nil)
1215 ;; Alist of split expressions their equivalent regexps.
1216
1217 (defun nnmail-split-it (split)
1218   ;; Return a list of groups matching SPLIT.
1219   (let (cached-pair)
1220     (cond
1221      ;; nil split
1222      ((null split)
1223       nil)
1224
1225      ;; A group name.  Do the \& and \N subs into the string.
1226      ((stringp split)
1227       (when nnmail-split-tracing
1228         (push (format "\"%s\"" split) nnmail-split-trace))
1229       (list (nnmail-expand-newtext split)))
1230
1231      ;; Junk the message.
1232      ((eq split 'junk)
1233       (when nnmail-split-tracing
1234         (push "junk" nnmail-split-trace))
1235       (list 'junk))
1236
1237      ;; Builtin & operation.
1238      ((eq (car split) '&)
1239       (apply 'nconc (mapcar 'nnmail-split-it (cdr split))))
1240
1241      ;; Builtin | operation.
1242      ((eq (car split) '|)
1243       (let (done)
1244         (while (and (not done) (cdr split))
1245           (setq split (cdr split)
1246                 done (nnmail-split-it (car split))))
1247         done))
1248
1249      ;; Builtin : operation.
1250      ((eq (car split) ':)
1251       (nnmail-split-it (save-excursion (eval (cdr split)))))
1252
1253      ;; Check the cache for the regexp for this split.
1254      ((setq cached-pair (assq split nnmail-split-cache))
1255       (goto-char (point-max))
1256       ;; FIX FIX FIX problem with re-search-backward is that if you have
1257       ;; a split: (from "foo-\\(bar\\|baz\\)@gnus.org "mail.foo.\\1")
1258       ;; and someone mails a message with 'To: foo-bar@gnus.org' and
1259       ;; 'CC: foo-baz@gnus.org', we'll pick 'mail.foo.baz' as the group
1260       ;; if the cc line is a later header, even though the other choice
1261       ;; is probably better.  Also, this routine won't do a crosspost
1262       ;; when there are two different matches.
1263       ;; I guess you could just make this more determined, and it could
1264       ;; look for still more matches prior to this one, and recurse
1265       ;; on each of the multiple matches hit.  Of course, then you'd
1266       ;; want to make sure that nnmail-article-group or nnmail-split-fancy
1267       ;; removed duplicates, since there might be more of those.
1268       ;; I guess we could also remove duplicates in the & split case, since
1269       ;; that's the only thing that can introduce them.
1270       (when (re-search-backward (cdr cached-pair) nil t)
1271         (when nnmail-split-tracing
1272           (push (cdr cached-pair) nnmail-split-trace))
1273         ;; Someone might want to do a \N sub on this match, so get the
1274         ;; correct match positions.
1275         (goto-char (match-end 0))
1276         (let ((value (nth 1 split)))
1277           (re-search-backward (if (symbolp value)
1278                                   (cdr (assq value nnmail-split-abbrev-alist))
1279                                 value)
1280                               (match-end 1)))
1281         (nnmail-split-it (nth 2 split))))
1282
1283      ;; Not in cache, compute a regexp for the field/value pair.
1284      (t
1285       (let* ((field (nth 0 split))
1286              (value (nth 1 split))
1287              (regexp (concat "^\\(\\("
1288                              (if (symbolp field)
1289                                  (cdr (assq field nnmail-split-abbrev-alist))
1290                                field)
1291                              "\\):.*\\)\\<\\("
1292                              (if (symbolp value)
1293                                  (cdr (assq value nnmail-split-abbrev-alist))
1294                                value)
1295                              "\\)\\>")))
1296         (push (cons split regexp) nnmail-split-cache)
1297         ;; Now that it's in the cache, just call nnmail-split-it again
1298         ;; on the same split, which will find it immediately in the cache.
1299         (nnmail-split-it split))))))
1300
1301 (defun nnmail-expand-newtext (newtext)
1302   (let ((len (length newtext))
1303         (pos 0)
1304         c expanded beg N did-expand)
1305     (while (< pos len)
1306       (setq beg pos)
1307       (while (and (< pos len)
1308                   (not (= (aref newtext pos) ?\\)))
1309         (setq pos (1+ pos)))
1310       (unless (= beg pos)
1311         (push (substring newtext beg pos) expanded))
1312       (when (< pos len)
1313         ;; We hit a \; expand it.
1314         (setq did-expand t
1315               pos (1+ pos)
1316               c (aref newtext pos))
1317         (if (not (or (= c ?\&)
1318                      (and (>= c ?1)
1319                           (<= c ?9))))
1320             ;; \ followed by some character we don't expand.
1321             (push (char-to-string c) expanded)
1322           ;; \& or \N
1323           (if (= c ?\&)
1324               (setq N 0)
1325             (setq N (- c ?0)))
1326           (when (match-beginning N)
1327             (push (buffer-substring (match-beginning N) (match-end N))
1328                   expanded))))
1329       (setq pos (1+ pos)))
1330     (if did-expand
1331         (apply 'concat (nreverse expanded))
1332       newtext)))
1333
1334 ;; Get a list of spool files to read.
1335 (defun nnmail-get-spool-files (&optional group)
1336   (if (null nnmail-spool-file)
1337       ;; No spool file whatsoever.
1338       nil
1339     (let* ((procmails
1340             ;; If procmail is used to get incoming mail, the files
1341             ;; are stored in this directory.
1342             (and (file-exists-p nnmail-procmail-directory)
1343                  (or (eq nnmail-spool-file 'procmail)
1344                      nnmail-use-procmail)
1345                  (directory-files
1346                   nnmail-procmail-directory
1347                   t (concat (if group (concat "^" (regexp-quote group)) "")
1348                             nnmail-procmail-suffix "$"))))
1349            (p procmails)
1350            (crash (when (and (file-exists-p nnmail-crash-box)
1351                              (> (nnheader-file-size
1352                                  (file-truename nnmail-crash-box))
1353                                 0))
1354                     (list nnmail-crash-box))))
1355       ;; Remove any directories that inadvertently match the procmail
1356       ;; suffix, which might happen if the suffix is "".
1357       (while p
1358         (when (file-directory-p (car p))
1359           (setq procmails (delete (car p) procmails)))
1360         (setq p (cdr p)))
1361       ;; Return the list of spools.
1362       (append
1363        crash
1364        (cond ((and group
1365                    (or (eq nnmail-spool-file 'procmail)
1366                        nnmail-use-procmail)
1367                    procmails)
1368               procmails)
1369              ((and group
1370                    (eq nnmail-spool-file 'procmail))
1371               nil)
1372              ((listp nnmail-spool-file)
1373               (nconc
1374                (apply
1375                 'nconc
1376                 (mapcar
1377                  (lambda (file)
1378                    (if (and (not (string-match "^po:" file))
1379                             (file-directory-p file))
1380                        (nnheader-directory-regular-files file)
1381                      (list file)))
1382                  nnmail-spool-file))
1383                procmails))
1384              ((stringp nnmail-spool-file)
1385               (if (and (not (string-match "^po:" nnmail-spool-file))
1386                        (file-directory-p nnmail-spool-file))
1387                   (nconc
1388                    (nnheader-directory-regular-files nnmail-spool-file)
1389                    procmails)
1390                 (cons nnmail-spool-file procmails)))
1391              ((eq nnmail-spool-file 'pop)
1392               (cons (format "po:%s" (user-login-name)) procmails))
1393              (t
1394               procmails))))))
1395
1396 ;; Activate a backend only if it isn't already activated.
1397 ;; If FORCE, re-read the active file even if the backend is
1398 ;; already activated.
1399 (defun nnmail-activate (backend &optional force)
1400   (nnheader-init-server-buffer)
1401   (let (file timestamp file-time)
1402     (if (or (not (symbol-value (intern (format "%s-group-alist" backend))))
1403             force
1404             (and (setq file (ignore-errors
1405                               (symbol-value (intern (format "%s-active-file"
1406                                                             backend)))))
1407                  (setq file-time (nth 5 (file-attributes file)))
1408                  (or (not
1409                       (setq timestamp
1410                             (condition-case ()
1411                                 (symbol-value (intern
1412                                                (format "%s-active-timestamp"
1413                                                        backend)))
1414                               (error 'none))))
1415                      (not (consp timestamp))
1416                      (equal timestamp '(0 0))
1417                      (> (nth 0 file-time) (nth 0 timestamp))
1418                      (and (= (nth 0 file-time) (nth 0 timestamp))
1419                           (> (nth 1 file-time) (nth 1 timestamp))))))
1420         (save-excursion
1421           (or (eq timestamp 'none)
1422               (set (intern (format "%s-active-timestamp" backend))
1423                    file-time))
1424           (funcall (intern (format "%s-request-list" backend)))))
1425     t))
1426
1427 (defun nnmail-message-id ()
1428   (concat "<" (message-unique-id) "@totally-fudged-out-message-id>"))
1429
1430 ;;;
1431 ;;; nnmail duplicate handling
1432 ;;;
1433
1434 (defvar nnmail-cache-buffer nil)
1435
1436 (defun nnmail-cache-open ()
1437   (if (or (not nnmail-treat-duplicates)
1438           (and nnmail-cache-buffer
1439                (buffer-name nnmail-cache-buffer)))
1440       ()                                ; The buffer is open.
1441     (save-excursion
1442       (set-buffer
1443        (setq nnmail-cache-buffer
1444              (get-buffer-create " *nnmail message-id cache*")))
1445       (buffer-disable-undo (current-buffer))
1446       (when (file-exists-p nnmail-message-id-cache-file)
1447         (nnheader-insert-file-contents nnmail-message-id-cache-file))
1448       (set-buffer-modified-p nil)
1449       (current-buffer))))
1450
1451 (defun nnmail-cache-close ()
1452   (when (and nnmail-cache-buffer
1453              nnmail-treat-duplicates
1454              (buffer-name nnmail-cache-buffer)
1455              (buffer-modified-p nnmail-cache-buffer))
1456     (save-excursion
1457       (set-buffer nnmail-cache-buffer)
1458       ;; Weed out the excess number of Message-IDs.
1459       (goto-char (point-max))
1460       (when (search-backward "\n" nil t nnmail-message-id-cache-length)
1461         (progn
1462           (beginning-of-line)
1463           (delete-region (point-min) (point))))
1464       ;; Save the buffer.
1465       (or (file-exists-p (file-name-directory nnmail-message-id-cache-file))
1466           (make-directory (file-name-directory nnmail-message-id-cache-file)
1467                           t))
1468       (nnmail-write-region (point-min) (point-max)
1469                            nnmail-message-id-cache-file nil 'silent)
1470       (set-buffer-modified-p nil)
1471       (setq nnmail-cache-buffer nil)
1472       (kill-buffer (current-buffer)))))
1473
1474 (defun nnmail-cache-insert (id)
1475   (when nnmail-treat-duplicates
1476     (unless (gnus-buffer-live-p nnmail-cache-buffer)
1477       (nnmail-cache-open))
1478     (save-excursion
1479       (set-buffer nnmail-cache-buffer)
1480       (goto-char (point-max))
1481       (insert id "\n"))))
1482
1483 (defun nnmail-cache-id-exists-p (id)
1484   (when nnmail-treat-duplicates
1485     (save-excursion
1486       (set-buffer nnmail-cache-buffer)
1487       (goto-char (point-max))
1488       (search-backward id nil t))))
1489
1490 (defun nnmail-fetch-field (header)
1491   (save-excursion
1492     (save-restriction
1493       (message-narrow-to-head)
1494       (message-fetch-field header))))
1495
1496 (defun nnmail-check-duplication (message-id func artnum-func)
1497   (run-hooks 'nnmail-prepare-incoming-message-hook)
1498   ;; If this is a duplicate message, then we do not save it.
1499   (let* ((duplication (nnmail-cache-id-exists-p message-id))
1500          (case-fold-search t)
1501          (action (when duplication
1502                    (cond
1503                     ((memq nnmail-treat-duplicates '(warn delete))
1504                      nnmail-treat-duplicates)
1505                     ((nnheader-functionp nnmail-treat-duplicates)
1506                      (funcall nnmail-treat-duplicates message-id))
1507                     (t
1508                      nnmail-treat-duplicates))))
1509          group-art)
1510     ;; Let the backend save the article (or not).
1511     (cond
1512      ((not duplication)
1513       (nnmail-cache-insert message-id)
1514       (funcall func (setq group-art
1515                           (nreverse (nnmail-article-group artnum-func)))))
1516      ((eq action 'delete)
1517       (setq group-art nil))
1518      ((eq action 'warn)
1519       ;; We insert a warning.
1520       (let ((case-fold-search t))
1521         (goto-char (point-min))
1522         (re-search-forward "^message-id[ \t]*:" nil t)
1523         (beginning-of-line)
1524         (insert
1525          "Gnus-Warning: This is a duplicate of message " message-id "\n")
1526         (funcall func (setq group-art
1527                             (nreverse (nnmail-article-group artnum-func))))))
1528      (t
1529       (funcall func (setq group-art
1530                           (nreverse (nnmail-article-group artnum-func))))))
1531     ;; Add the group-art list to the history list.
1532     (if group-art
1533         (push group-art nnmail-split-history)
1534       (delete-region (point-min) (point-max)))))
1535
1536 ;;; Get new mail.
1537
1538 (defun nnmail-get-value (&rest args)
1539   (let ((sym (intern (apply 'format args))))
1540     (when (boundp sym)
1541       (symbol-value sym))))
1542
1543 (defun nnmail-get-new-mail (method exit-func temp
1544                                    &optional group spool-func)
1545   "Read new incoming mail."
1546   (let* ((spools (nnmail-get-spool-files group))
1547          (group-in group)
1548          nnmail-current-spool incoming incomings spool)
1549     (when (and (nnmail-get-value "%s-get-new-mail" method)
1550                nnmail-spool-file)
1551       ;; We first activate all the groups.
1552       (nnmail-activate method)
1553       ;; Allow the user to hook.
1554       (run-hooks 'nnmail-pre-get-new-mail-hook)
1555       ;; Open the message-id cache.
1556       (nnmail-cache-open)
1557       ;; The we go through all the existing spool files and split the
1558       ;; mail from each.
1559       (while spools
1560         (setq spool (pop spools))
1561         ;; We read each spool file if either the spool is a POP-mail
1562         ;; spool, or the file exists.  We can't check for the
1563         ;; existence of POPped mail.
1564         (when (or (string-match "^po:" spool)
1565                   (and (file-exists-p (file-truename spool))
1566                        (> (nnheader-file-size (file-truename spool)) 0)))
1567           (nnheader-message 3 "%s: Reading incoming mail..." method)
1568           (when (and (nnmail-move-inbox spool)
1569                      (file-exists-p nnmail-crash-box))
1570             (setq nnmail-current-spool spool)
1571             ;; There is new mail.  We first find out if all this mail
1572             ;; is supposed to go to some specific group.
1573             (setq group (nnmail-get-split-group spool group-in))
1574             ;; We split the mail
1575             (nnmail-split-incoming
1576              nnmail-crash-box (intern (format "%s-save-mail" method))
1577              spool-func group (intern (format "%s-active-number" method)))
1578             ;; Check whether the inbox is to be moved to the special tmp dir.
1579             (setq incoming
1580                   (nnmail-make-complex-temp-name
1581                    (expand-file-name
1582                     (if nnmail-tmp-directory
1583                         (concat
1584                          (file-name-as-directory nnmail-tmp-directory)
1585                          (file-name-nondirectory
1586                           (concat (file-name-as-directory temp) "Incoming")))
1587                       (concat (file-name-as-directory temp) "Incoming")))))
1588             (unless (file-exists-p (file-name-directory incoming))
1589               (make-directory (file-name-directory incoming) t))
1590             (rename-file nnmail-crash-box incoming t)
1591             (push incoming incomings))))
1592       ;; If we did indeed read any incoming spools, we save all info.
1593       (when incomings
1594         (nnmail-save-active
1595          (nnmail-get-value "%s-group-alist" method)
1596          (nnmail-get-value "%s-active-file" method))
1597         (when exit-func
1598           (funcall exit-func))
1599         (run-hooks 'nnmail-read-incoming-hook)
1600         (nnheader-message 3 "%s: Reading incoming mail...done" method))
1601       ;; Close the message-id cache.
1602       (nnmail-cache-close)
1603       ;; Allow the user to hook.
1604       (run-hooks 'nnmail-post-get-new-mail-hook)
1605       ;; Delete all the temporary files.
1606       (while incomings
1607         (setq incoming (pop incomings))
1608         (and nnmail-delete-incoming
1609              (file-exists-p incoming)
1610              (file-writable-p incoming)
1611              (delete-file incoming))))))
1612
1613 (defun nnmail-expired-article-p (group time force &optional inhibit)
1614   "Say whether an article that is TIME old in GROUP should be expired."
1615   (if force
1616       t
1617     (let ((days (or (and nnmail-expiry-wait-function
1618                          (funcall nnmail-expiry-wait-function group))
1619                     nnmail-expiry-wait)))
1620       (cond ((or (eq days 'never)
1621                  (and (not force)
1622                       inhibit))
1623              ;; This isn't an expirable group.
1624              nil)
1625             ((eq days 'immediate)
1626              ;; We expire all articles on sight.
1627              t)
1628             ((equal time '(0 0))
1629              ;; This is an ange-ftp group, and we don't have any dates.
1630              nil)
1631             ((numberp days)
1632              (setq days (days-to-time days))
1633              ;; Compare the time with the current time.
1634              (time-less-p days (time-since time)))))))
1635
1636 (defvar nnmail-read-passwd nil)
1637 (defun nnmail-read-passwd (prompt &rest args)
1638   "Read a password using PROMPT.
1639 If ARGS, PROMPT is used as an argument to `format'."
1640   (let ((prompt
1641          (if args
1642              (apply 'format prompt args)
1643            prompt)))
1644     (unless nnmail-read-passwd
1645       (if (load "passwd" t)
1646           (setq nnmail-read-passwd 'read-passwd)
1647         (unless (fboundp 'ange-ftp-read-passwd)
1648           (autoload 'ange-ftp-read-passwd "ange-ftp"))
1649         (setq nnmail-read-passwd 'ange-ftp-read-passwd)))
1650     (funcall nnmail-read-passwd prompt)))
1651
1652 (defun nnmail-check-syntax ()
1653   "Check (and modify) the syntax of the message in the current buffer."
1654   (save-restriction
1655     (message-narrow-to-head)
1656     (let ((case-fold-search t))
1657       (unless (re-search-forward "^Message-ID[ \t]*:" nil t)
1658         (insert "Message-ID: " (nnmail-message-id) "\n")))))
1659
1660 (defun nnmail-write-region (start end filename &optional append visit lockname)
1661   "Do a `write-region', and then set the file modes."
1662   (let ((coding-system-for-write nnmail-file-coding-system)
1663         (pathname-coding-system 'binary))
1664     (write-region start end filename append visit lockname)
1665     (set-file-modes filename nnmail-default-file-modes)))
1666
1667 ;;;
1668 ;;; Status functions
1669 ;;;
1670
1671 (defun nnmail-replace-status (name value)
1672   "Make status NAME and VALUE part of the current status line."
1673   (save-restriction
1674     (message-narrow-to-head)
1675     (let ((status (nnmail-decode-status)))
1676       (setq status (delq (member name status) status))
1677       (when value
1678         (push (cons name value) status))
1679       (message-remove-header "status")
1680       (goto-char (point-max))
1681       (insert "Status: " (nnmail-encode-status status) "\n"))))
1682
1683 (defun nnmail-decode-status ()
1684   "Return a status-value alist from STATUS."
1685   (goto-char (point-min))
1686   (when (re-search-forward "^Status: " nil t)
1687     (let (name value status)
1688       (save-restriction
1689         ;; Narrow to the status.
1690         (narrow-to-region
1691          (point)
1692          (if (re-search-forward "^[^ \t]" nil t)
1693              (1- (point))
1694            (point-max)))
1695         ;; Go through all elements and add them to the list.
1696         (goto-char (point-min))
1697         (while (re-search-forward "[^ \t=]+" nil t)
1698           (setq name (match-string 0))
1699           (if (not (= (following-char) ?=))
1700               ;; Implied "yes".
1701               (setq value "yes")
1702             (forward-char 1)
1703             (if (not (= (following-char) ?\"))
1704                 (if (not (looking-at "[^ \t]"))
1705                     ;; Implied "no".
1706                     (setq value "no")
1707                   ;; Unquoted value.
1708                   (setq value (match-string 0))
1709                   (goto-char (match-end 0)))
1710               ;; Quoted value.
1711               (setq value (read (current-buffer)))))
1712           (push (cons name value) status)))
1713       status)))
1714
1715 (defun nnmail-encode-status (status)
1716   "Return a status string from STATUS."
1717   (mapconcat
1718    (lambda (elem)
1719      (concat
1720       (car elem) "="
1721       (if (string-match "[ \t]" (cdr elem))
1722           (prin1-to-string (cdr elem))
1723         (cdr elem))))
1724    status " "))
1725
1726 (defun nnmail-split-history ()
1727   "Generate an overview of where the last mail split put articles."
1728   (interactive)
1729   (unless nnmail-split-history
1730     (error "No current split history"))
1731   (with-output-to-temp-buffer "*nnmail split history*"
1732     (let ((history nnmail-split-history)
1733           elem)
1734       (while (setq elem (pop history))
1735         (princ (mapconcat (lambda (ga)
1736                             (concat (car ga) ":" (int-to-string (cdr ga))))
1737                           elem
1738                           ", "))
1739         (princ "\n")))))
1740
1741 (defun nnmail-purge-split-history (group)
1742   "Remove all instances of GROUP from `nnmail-split-history'."
1743   (let ((history nnmail-split-history))
1744     (while history
1745       (setcar history (gnus-delete-if (lambda (e) (string= (car e) group))
1746                                       (car history)))
1747       (pop history))
1748     (setq nnmail-split-history (delq nil nnmail-split-history))))
1749
1750 (defun nnmail-new-mail-p (group)
1751   "Say whether GROUP has new mail."
1752   (let ((his nnmail-split-history)
1753         found)
1754     (while his
1755       (when (assoc group (pop his))
1756         (setq found t
1757               his nil)))
1758     found))
1759
1760 (eval-and-compile
1761   (autoload 'pop3-movemail "pop3"))
1762
1763 (defun nnmail-pop3-movemail (inbox crashbox)
1764   "Function to move mail from INBOX on a pop3 server to file CRASHBOX."
1765   (let ((pop3-maildrop
1766          (substring inbox (match-end (string-match "^po:" inbox)))))
1767     (pop3-movemail crashbox)))
1768
1769 (defun nnmail-within-headers-p ()
1770   "Check to see if point is within the headers of a unix mail message.
1771 Doesn't change point."
1772   (let ((pos (point)))
1773     (save-excursion
1774       (and (nnmail-search-unix-mail-delim-backward)
1775            (not (search-forward "\n\n" pos t))))))
1776
1777 (run-hooks 'nnmail-load-hook)
1778
1779 (provide 'nnmail)
1780
1781 ;;; nnmail.el ends here