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