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