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