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