Importing gnus-5.6.24
[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
35 (eval-and-compile
36   (autoload 'gnus-error "gnus-util")
37   (autoload 'gnus-buffer-live-p "gnus-util")
38   (autoload 'gnus-encode-coding-string "gnus-ems"))
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 'file)
185
186 (defcustom nnmail-crash-box "~/.gnus-crash-box"
187   "File where Gnus will store mail while processing it."
188   :group 'nnmail-files
189   :type 'file)
190
191 (defcustom nnmail-use-procmail nil
192   "*If non-nil, the mail backends will look in `nnmail-procmail-directory' for spool files.
193 The file(s) in `nnmail-spool-file' will also be read."
194   :group 'nnmail-procmail
195   :type 'boolean)
196
197 (defcustom nnmail-procmail-directory "~/incoming/"
198   "*When using procmail (and the like), incoming mail is put in this directory.
199 The Gnus mail backends will read the mail from this directory."
200   :group 'nnmail-procmail
201   :type 'directory)
202
203 (defcustom nnmail-procmail-suffix "\\.spool"
204   "*Suffix of files created by procmail (and the like).
205 This variable might be a suffix-regexp to match the suffixes of
206 several files - eg. \".spool[0-9]*\"."
207   :group 'nnmail-procmail
208   :type 'regexp)
209
210 (defcustom nnmail-resplit-incoming nil
211   "*If non-nil, re-split incoming procmail sorted mail."
212   :group 'nnmail-procmail
213   :type 'boolean)
214
215 (defcustom nnmail-delete-file-function 'delete-file
216   "Function called to delete files in some mail backends."
217   :group 'nnmail-files
218   :type 'function)
219
220 (defcustom nnmail-crosspost-link-function
221   (if (string-match "windows-nt\\|emx" (symbol-name system-type))
222       'copy-file
223     'add-name-to-file)
224   "*Function called to create a copy of a file.
225 This is `add-name-to-file' by default, which means that crossposts
226 will use hard links.  If your file system doesn't allow hard
227 links, you could set this variable to `copy-file' instead."
228   :group 'nnmail-files
229   :type '(radio (function-item add-name-to-file)
230                 (function-item copy-file)
231                 (function :tag "Other")))
232
233 (defcustom nnmail-movemail-program "movemail"
234   "*A command to be executed to move mail from the inbox.
235 The default is \"movemail\".
236
237 This can also be a function.  In that case, the function will be
238 called with two parameters -- the name of the INBOX file, and the file
239 to be moved to."
240   :group 'nnmail-files
241   :group 'nnmail-retrieve
242   :type 'string)
243
244 (defcustom nnmail-pop-password-required nil
245   "*Non-nil if a password is required when reading mail using POP."
246   :group 'nnmail-retrieve
247   :type 'boolean)
248
249 (defcustom nnmail-read-incoming-hook
250   (if (eq system-type 'windows-nt)
251       '(nnheader-ms-strip-cr)
252     nil)
253   "*Hook that will be run after the incoming mail has been transferred.
254 The incoming mail is moved from `nnmail-spool-file' (which normally is
255 something like \"/usr/spool/mail/$user\") to the user's home
256 directory.  This hook is called after the incoming mail box has been
257 emptied, and can be used to call any mail box programs you have
258 running (\"xwatch\", etc.)
259
260 Eg.
261
262 \(add-hook 'nnmail-read-incoming-hook
263            (lambda ()
264              (start-process \"mailsend\" nil
265                             \"/local/bin/mailsend\" \"read\" \"mbox\")))
266
267 If you have xwatch running, this will alert it that mail has been
268 read.
269
270 If you use `display-time', you could use something like this:
271
272 \(add-hook 'nnmail-read-incoming-hook
273           (lambda ()
274             ;; Update the displayed time, since that will clear out
275             ;; the flag that says you have mail.
276             (when (eq (process-status \"display-time\") 'run)
277               (display-time-filter display-time-process \"\"))))"
278   :group 'nnmail-prepare
279   :type 'hook)
280
281 ;; Suggested by Erik Selberg <speed@cs.washington.edu>.
282 (defcustom nnmail-prepare-incoming-hook nil
283   "Hook called before treating incoming mail.
284 The hook is run in a buffer with all the new, incoming mail."
285   :group 'nnmail-prepare
286   :type 'hook)
287
288 (defcustom nnmail-prepare-incoming-header-hook nil
289   "Hook called narrowed to the headers of each message.
290 This can be used to remove excessive spaces (and stuff like
291 that) from the headers before splitting and saving the messages."
292   :group 'nnmail-prepare
293   :type 'hook)
294
295 (defcustom nnmail-prepare-incoming-message-hook nil
296   "Hook called narrowed to each message."
297   :group 'nnmail-prepare
298   :type 'hook)
299
300 (defcustom nnmail-list-identifiers nil
301   "Regexp that matches list identifiers to be removed.
302 This can also be a list of regexps."
303   :group 'nnmail-prepare
304   :type '(choice (const :tag "none" nil)
305                  (regexp :value ".*")
306                  (repeat :value (".*") regexp)))
307
308 (defcustom nnmail-pre-get-new-mail-hook nil
309   "Hook called just before starting to handle new incoming mail."
310   :group 'nnmail-retrieve
311   :type 'hook)
312
313 (defcustom nnmail-post-get-new-mail-hook nil
314   "Hook called just after finishing handling new incoming mail."
315   :group 'nnmail-retrieve
316   :type 'hook)
317
318 (defcustom nnmail-split-hook nil
319   "Hook called before deciding where to split an article.
320 The functions in this hook are free to modify the buffer
321 contents in any way they choose -- the buffer contents are
322 discarded after running the split process."
323   :group 'nnmail-split
324   :type 'hook)
325
326 ;; Suggested by Mejia Pablo J <pjm9806@usl.edu>.
327 (defcustom nnmail-tmp-directory nil
328   "*If non-nil, use this directory for temporary storage.
329 Used when reading incoming mail."
330   :group 'nnmail-files
331   :group 'nnmail-retrieve
332   :type '(choice (const :tag "default" nil)
333                  (directory :format "%v")))
334
335 (defcustom nnmail-large-newsgroup 50
336   "*The number of the articles which indicates a large newsgroup.
337 If the number of the articles is greater than the value, verbose
338 messages will be shown to indicate the current status."
339   :group 'nnmail-various
340   :type 'integer)
341
342 (defcustom nnmail-split-fancy "mail.misc"
343   "Incoming mail can be split according to this fancy variable.
344 To enable this, set `nnmail-split-methods' to `nnmail-split-fancy'.
345
346 The format of this variable is SPLIT, where SPLIT can be one of
347 the following:
348
349 GROUP: Mail will be stored in GROUP (a string).
350
351 \(FIELD VALUE SPLIT): If the message field FIELD (a regexp) contains
352   VALUE (a regexp), store the messages as specified by SPLIT.
353
354 \(| SPLIT...): Process each SPLIT expression until one of them matches.
355   A SPLIT expression is said to match if it will cause the mail
356   message to be stored in one or more groups.
357
358 \(& SPLIT...): Process each SPLIT expression.
359
360 \(: FUNCTION optional args): Call FUNCTION with the optional args, in
361   the buffer containing the message headers.  The return value FUNCTION
362   should be a split, which is then recursively processed.
363
364 FIELD must match a complete field name.  VALUE must match a complete
365 word according to the `nnmail-split-fancy-syntax-table' syntax table.
366 You can use \".*\" in the regexps to match partial field names or words.
367
368 FIELD and VALUE can also be lisp symbols, in that case they are expanded
369 as specified in `nnmail-split-abbrev-alist'.
370
371 GROUP can contain \\& and \\N which will substitute from matching
372 \\(\\) patterns in the previous VALUE.
373
374 Example:
375
376 \(setq nnmail-split-methods 'nnmail-split-fancy
377       nnmail-split-fancy
378       ;; Messages from the mailer daemon are not crossposted to any of
379       ;; the ordinary groups.  Warnings are put in a separate group
380       ;; from real errors.
381       '(| (\"from\" mail (| (\"subject\" \"warn.*\" \"mail.warning\")
382                           \"mail.misc\"))
383           ;; Non-error messages are crossposted to all relevant
384           ;; groups, but we don't crosspost between the group for the
385           ;; (ding) list and the group for other (ding) related mail.
386           (& (| (any \"ding@ifi\\\\.uio\\\\.no\" \"ding.list\")
387                 (\"subject\" \"ding\" \"ding.misc\"))
388              ;; Other mailing lists...
389              (any \"procmail@informatik\\\\.rwth-aachen\\\\.de\" \"procmail.list\")
390              (any \"SmartList@informatik\\\\.rwth-aachen\\\\.de\" \"SmartList.list\")
391              ;; People...
392              (any \"larsi@ifi\\\\.uio\\\\.no\" \"people.Lars Magne Ingebrigtsen\"))
393           ;; Unmatched mail goes to the catch all group.
394           \"misc.misc\"))"
395   :group 'nnmail-split
396   ;; Sigh!
397   :type 'sexp)
398
399 (defcustom nnmail-split-abbrev-alist
400   '((any . "from\\|to\\|cc\\|sender\\|apparently-to\\|resent-from\\|resent-to\\|resent-cc")
401     (mail . "mailer-daemon\\|postmaster\\|uucp")
402     (to . "to\\|cc\\|apparently-to\\|resent-to\\|resent-cc")
403     (from . "from\\|sender\\|resent-from")
404     (nato . "to\\|cc\\|resent-to\\|resent-cc")
405     (naany . "from\\|to\\|cc\\|sender\\|resent-from\\|resent-to\\|resent-cc"))
406   "*Alist of abbreviations allowed in `nnmail-split-fancy'."
407   :group 'nnmail-split
408   :type '(repeat (cons :format "%v" symbol regexp)))
409
410 (defcustom nnmail-delete-incoming t
411   "*If non-nil, the mail backends will delete incoming files after
412 splitting."
413   :group 'nnmail-retrieve
414   :type 'boolean)
415
416 (defcustom nnmail-message-id-cache-length 1000
417   "*The approximate number of Message-IDs nnmail will keep in its cache.
418 If this variable is nil, no checking on duplicate messages will be
419 performed."
420   :group 'nnmail-duplicate
421   :type '(choice (const :tag "disable" nil)
422                  (integer :format "%v")))
423
424 (defcustom nnmail-message-id-cache-file "~/.nnmail-cache"
425   "*The file name of the nnmail Message-ID cache."
426   :group 'nnmail-duplicate
427   :group 'nnmail-files
428   :type 'file)
429
430 (defcustom nnmail-treat-duplicates 'warn
431   "*If non-nil, nnmail keep a cache of Message-IDs to discover mail duplicates.
432 Three values are legal: nil, which means that nnmail is not to keep a
433 Message-ID cache; `warn', which means that nnmail should insert extra
434 headers to warn the user about the duplication (this is the default);
435 and `delete', which means that nnmail will delete duplicated mails.
436
437 This variable can also be a function.  It will be called from a buffer
438 narrowed to the article in question with the Message-ID as a
439 parameter.  It should return nil, `warn' or `delete'."
440   :group 'nnmail-duplicate
441   :type '(choice (const :tag "off" nil)
442                  (const warn)
443                  (const delete)))
444
445 ;;; Internal variables.
446
447 (defvar nnmail-split-history nil
448   "List of group/article elements that say where the previous split put messages.")
449
450 (defvar nnmail-current-spool nil)
451
452 (defvar nnmail-pop-password nil
453   "*Password to use when reading mail from a POP server, if required.")
454
455 (defvar nnmail-split-fancy-syntax-table nil
456   "Syntax table used by `nnmail-split-fancy'.")
457 (unless (syntax-table-p nnmail-split-fancy-syntax-table)
458   (setq nnmail-split-fancy-syntax-table
459         (copy-syntax-table (standard-syntax-table)))
460   ;; support the %-hack
461   (modify-syntax-entry ?\% "." nnmail-split-fancy-syntax-table))
462
463 (defvar nnmail-prepare-save-mail-hook nil
464   "Hook called before saving mail.")
465
466 (defvar nnmail-moved-inboxes nil
467   "List of inboxes that have been moved.")
468
469 (defvar nnmail-internal-password nil)
470
471 (defvar nnmail-split-tracing nil)
472 (defvar nnmail-split-trace nil)
473
474 \f
475
476 (defconst nnmail-version "nnmail 1.0"
477   "nnmail version.")
478
479 \f
480
481 (defun nnmail-request-post (&optional server)
482   (mail-send-and-exit nil))
483
484 (defvar nnmail-file-coding-system 'raw-text
485   "Coding system used in nnmail.")
486
487 (defun nnmail-find-file (file)
488   "Insert FILE in server buffer safely."
489   (set-buffer nntp-server-buffer)
490   (erase-buffer)
491   (let ((format-alist nil)
492         (after-insert-file-functions nil))
493     (condition-case ()
494         (let ((coding-system-for-read nnmail-file-coding-system)
495               (pathname-coding-system 'binary))
496           (insert-file-contents file)
497           t)
498       (file-error nil))))
499
500 (defvar nnmail-pathname-coding-system
501   'iso-8859-1
502   "*Coding system for pathname.")
503
504 (defun nnmail-group-pathname (group dir &optional file)
505   "Make pathname for GROUP."
506   (concat
507    (let ((dir (file-name-as-directory (expand-file-name dir))))
508      (setq group (nnheader-translate-file-chars group))
509      ;; If this directory exists, we use it directly.
510      (if (or nnmail-use-long-file-names
511              (file-directory-p (concat dir group)))
512          (concat dir group "/")
513        ;; If not, we translate dots into slashes.
514        (concat dir
515                (gnus-encode-coding-string
516                 (nnheader-replace-chars-in-string group ?. ?/)
517                 nnmail-pathname-coding-system)
518                "/")))
519    (or file "")))
520
521 (defun nnmail-date-to-time (date)
522   "Convert DATE into time."
523   (condition-case ()
524       (let* ((d1 (timezone-parse-date date))
525              (t1 (timezone-parse-time (aref d1 3))))
526         (apply 'encode-time
527                (mapcar (lambda (el)
528                          (and el (string-to-number el)))
529                        (list
530                         (aref t1 2) (aref t1 1) (aref t1 0)
531                         (aref d1 2) (aref d1 1) (aref d1 0)
532                         (number-to-string
533                          (* 60 (timezone-zone-to-minute (aref d1 4))))))))
534     ;; If we get an error, then we just return a 0 time.
535     (error (list 0 0))))
536
537 (defun nnmail-time-less (t1 t2)
538   "Say whether time T1 is less than time T2."
539   (or (< (car t1) (car t2))
540       (and (= (car t1) (car t2))
541            (< (nth 1 t1) (nth 1 t2)))))
542
543 (defun nnmail-days-to-time (days)
544   "Convert DAYS into time."
545   (let* ((seconds (* 1.0 days 60 60 24))
546          (rest (expt 2 16))
547          (ms (condition-case nil (floor (/ seconds rest))
548                (range-error (expt 2 16)))))
549     (list ms (condition-case nil (round (- seconds (* ms rest)))
550                (range-error (expt 2 16))))))
551
552 (defun nnmail-time-since (time)
553   "Return the time since TIME, which is either an internal time or a date."
554   (when (stringp time)
555     ;; Convert date strings to internal time.
556     (setq time (nnmail-date-to-time time)))
557   (let* ((current (current-time))
558          (rest (when (< (nth 1 current) (nth 1 time))
559                  (expt 2 16))))
560     (list (- (+ (car current) (if rest -1 0)) (car time))
561           (- (+ (or rest 0) (nth 1 current)) (nth 1 time)))))
562
563 ;; Function rewritten from rmail.el.
564 (defun nnmail-move-inbox (inbox)
565   "Move INBOX to `nnmail-crash-box'."
566   (if (not (file-writable-p nnmail-crash-box))
567       (gnus-error 1 "Can't write to crash box %s.  Not moving mail"
568                   nnmail-crash-box)
569     ;; If the crash box exists and is empty, we delete it.
570     (when (and (file-exists-p nnmail-crash-box)
571                (zerop (nnheader-file-size (file-truename nnmail-crash-box))))
572       (delete-file nnmail-crash-box))
573     (let ((tofile (file-truename (expand-file-name nnmail-crash-box)))
574           (popmail (string-match "^po:" inbox))
575           movemail errors result)
576       (unless popmail
577         (setq inbox (file-truename (expand-file-name inbox)))
578         (setq movemail t)
579         ;; On some systems, /usr/spool/mail/foo is a directory
580         ;; and the actual inbox is /usr/spool/mail/foo/foo.
581         (when (file-directory-p inbox)
582           (setq inbox (expand-file-name (user-login-name) inbox))))
583       (if (member inbox nnmail-moved-inboxes)
584           ;; We don't try to move an already moved inbox.
585           nil
586         (if popmail
587             (progn
588               (when (and nnmail-pop-password
589                          (not nnmail-internal-password))
590                 (setq nnmail-internal-password nnmail-pop-password))
591               (when (and nnmail-pop-password-required
592                          (not nnmail-internal-password))
593                 (setq nnmail-internal-password
594                       (nnmail-read-passwd
595                        (format "Password for %s: "
596                                (substring inbox (+ popmail 3))))))
597               (nnheader-message 5 "Getting mail from the post office..."))
598           (when (or (and (file-exists-p tofile)
599                          (/= 0 (nnheader-file-size tofile)))
600                     (and (file-exists-p inbox)
601                          (/= 0 (nnheader-file-size inbox))))
602             (nnheader-message 5 "Getting mail from %s..." inbox)))
603         ;; Set TOFILE if have not already done so, and
604         ;; rename or copy the file INBOX to TOFILE if and as appropriate.
605         (cond
606          ((file-exists-p tofile)
607           ;; The crash box exists already.
608           t)
609          ((and (not popmail)
610                (not (file-exists-p inbox)))
611           ;; There is no inbox.
612           (setq tofile nil))
613          (t
614           ;; If getting from mail spool directory, use movemail to move
615           ;; rather than just renaming, so as to interlock with the
616           ;; mailer.
617           (unwind-protect
618               (save-excursion
619                 (setq errors (generate-new-buffer " *nnmail loss*"))
620                 (buffer-disable-undo errors)
621                 (if (nnheader-functionp nnmail-movemail-program)
622                     (condition-case err
623                         (progn
624                           (funcall nnmail-movemail-program inbox tofile)
625                           (setq result 0))
626                       (error
627                        (save-excursion
628                          (set-buffer errors)
629                          (insert (prin1-to-string err))
630                          (setq result 255))))
631                   (let ((default-directory "/"))
632                     (setq result
633                           (apply
634                            'call-process
635                            (append
636                             (list
637                              (expand-file-name
638                               nnmail-movemail-program exec-directory)
639                              nil errors nil inbox tofile)
640                             (when nnmail-internal-password
641                               (list nnmail-internal-password)))))))
642                 (push inbox nnmail-moved-inboxes)
643                 (if (and (not (buffer-modified-p errors))
644                          (zerop result))
645                     ;; No output => movemail won
646                     (progn
647                       (unless popmail
648                         (when (file-exists-p tofile)
649                           (set-file-modes tofile nnmail-default-file-modes))))
650                   (set-buffer errors)
651                   ;; There may be a warning about older revisions.  We
652                   ;; ignore those.
653                   (goto-char (point-min))
654                   (if (search-forward "older revision" nil t)
655                       (progn
656                         (unless popmail
657                           (when (file-exists-p tofile)
658                             (set-file-modes
659                              tofile nnmail-default-file-modes))))
660                     ;; Probably a real error.
661                     (subst-char-in-region (point-min) (point-max) ?\n ?\  )
662                     (goto-char (point-max))
663                     (skip-chars-backward " \t")
664                     (delete-region (point) (point-max))
665                     (goto-char (point-min))
666                     (when (looking-at "movemail: ")
667                       (delete-region (point-min) (match-end 0)))
668                     (unless (yes-or-no-p
669                              (format "movemail: %s (%d return).  Continue? "
670                                      (buffer-string) result))
671                       (error "%s" (buffer-string)))
672                     (setq tofile nil)))))))
673         (nnheader-message 5 "Getting mail from %s...done" inbox)
674         (and errors
675              (buffer-name errors)
676              (kill-buffer errors))
677         tofile))))
678
679 (defun nnmail-get-active ()
680   "Returns an assoc of group names and active ranges.
681 nn*-request-list should have been called before calling this function."
682   (let (group-assoc)
683     ;; Go through all groups from the active list.
684     (save-excursion
685       (set-buffer nntp-server-buffer)
686       (goto-char (point-min))
687       (while (re-search-forward
688               "^\\([^ \t]+\\)[ \t]+\\([0-9]+\\)[ \t]+\\([0-9]+\\)" nil t)
689         ;; We create an alist with `(GROUP (LOW . HIGH))' elements.
690         (push (list (match-string 1)
691                     (cons (string-to-int (match-string 3))
692                           (string-to-int (match-string 2))))
693               group-assoc)))
694     group-assoc))
695
696 (defvar nnmail-active-file-coding-system
697   'iso-8859-1
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