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