3124586159e17115b7355b562da0270aaa29550a
[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                (nnheader-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                         (nnheader-encode-coding-string
1205                          (caar group-alist)
1206                          nnmail-pathname-coding-system)
1207                         (cdar group-alist)))
1208         (setq group-alist (cdr group-alist)))
1209       (insert "\n"))))
1210
1211 ;;; Message washing functions
1212
1213 (defun nnmail-remove-leading-whitespace ()
1214   "Remove excessive whitespace from all headers."
1215   (goto-char (point-min))
1216   (while (re-search-forward "^\\([^ :]+: \\) +" nil t)
1217     (replace-match "\\1" t)))
1218
1219 (defun nnmail-remove-list-identifiers ()
1220   "Remove list identifiers from Subject headers."
1221   (let ((regexp (if (stringp nnmail-list-identifiers) nnmail-list-identifiers
1222                   (mapconcat 'identity nnmail-list-identifiers "\\|"))))
1223     (when regexp
1224       (goto-char (point-min))
1225       (when (re-search-forward
1226              (concat "^Subject: +\\(Re: +\\)?\\(" regexp "\\) *")
1227              nil t)
1228         (delete-region (match-beginning 2) (match-end 0))))))
1229
1230 (defun nnmail-remove-tabs ()
1231   "Translate TAB characters into SPACE characters."
1232   (subst-char-in-region (point-min) (point-max) ?\t ?  t))
1233
1234 ;;; Utility functions
1235
1236 (defun nnmail-make-complex-temp-name (prefix)
1237   (let ((newname (make-temp-name prefix))
1238         (newprefix prefix))
1239     (while (file-exists-p newname)
1240       (setq newprefix (concat newprefix "x"))
1241       (setq newname (make-temp-name newprefix)))
1242     newname))
1243
1244 ;; Written by Per Abrahamsen <amanda@iesd.auc.dk>.
1245
1246 (defun nnmail-split-fancy ()
1247   "Fancy splitting method.
1248 See the documentation for the variable `nnmail-split-fancy' for documentation."
1249   (let ((syntab (syntax-table)))
1250     (unwind-protect
1251         (progn
1252           (set-syntax-table nnmail-split-fancy-syntax-table)
1253           (nnmail-split-it nnmail-split-fancy))
1254       (set-syntax-table syntab))))
1255
1256 (defvar nnmail-split-cache nil)
1257 ;; Alist of split expressions their equivalent regexps.
1258
1259 (defun nnmail-split-it (split)
1260   ;; Return a list of groups matching SPLIT.
1261   (let (cached-pair)
1262     (cond
1263      ;; nil split
1264      ((null split)
1265       nil)
1266
1267      ;; A group name.  Do the \& and \N subs into the string.
1268      ((stringp split)
1269       (when nnmail-split-tracing
1270         (push (format "\"%s\"" split) nnmail-split-trace))
1271       (list (nnmail-expand-newtext split)))
1272
1273      ;; Junk the message.
1274      ((eq split 'junk)
1275       (when nnmail-split-tracing
1276         (push "junk" nnmail-split-trace))
1277       (list 'junk))
1278
1279      ;; Builtin & operation.
1280      ((eq (car split) '&)
1281       (apply 'nconc (mapcar 'nnmail-split-it (cdr split))))
1282
1283      ;; Builtin | operation.
1284      ((eq (car split) '|)
1285       (let (done)
1286         (while (and (not done) (cdr split))
1287           (setq split (cdr split)
1288                 done (nnmail-split-it (car split))))
1289         done))
1290
1291      ;; Builtin : operation.
1292      ((eq (car split) ':)
1293       (nnmail-split-it (save-excursion (eval (cdr split)))))
1294
1295      ;; Check the cache for the regexp for this split.
1296      ((setq cached-pair (assq split nnmail-split-cache))
1297       (goto-char (point-max))
1298       ;; FIX FIX FIX problem with re-search-backward is that if you have
1299       ;; a split: (from "foo-\\(bar\\|baz\\)@gnus.org "mail.foo.\\1")
1300       ;; and someone mails a message with 'To: foo-bar@gnus.org' and
1301       ;; 'CC: foo-baz@gnus.org', we'll pick 'mail.foo.baz' as the group
1302       ;; if the cc line is a later header, even though the other choice
1303       ;; is probably better.  Also, this routine won't do a crosspost
1304       ;; when there are two different matches.
1305       ;; I guess you could just make this more determined, and it could
1306       ;; look for still more matches prior to this one, and recurse
1307       ;; on each of the multiple matches hit.  Of course, then you'd
1308       ;; want to make sure that nnmail-article-group or nnmail-split-fancy
1309       ;; removed duplicates, since there might be more of those.
1310       ;; I guess we could also remove duplicates in the & split case, since
1311       ;; that's the only thing that can introduce them.
1312       (when (re-search-backward (cdr cached-pair) nil t)
1313         (when nnmail-split-tracing
1314           (push (cdr cached-pair) nnmail-split-trace))
1315         ;; Someone might want to do a \N sub on this match, so get the
1316         ;; correct match positions.
1317         (goto-char (match-end 0))
1318         (let ((value (nth 1 split)))
1319           (re-search-backward (if (symbolp value)
1320                                   (cdr (assq value nnmail-split-abbrev-alist))
1321                                 value)
1322                               (match-end 1)))
1323         (nnmail-split-it (nth 2 split))))
1324
1325      ;; Not in cache, compute a regexp for the field/value pair.
1326      (t
1327       (let* ((field (nth 0 split))
1328              (value (nth 1 split))
1329              (regexp (concat "^\\(\\("
1330                              (if (symbolp field)
1331                                  (cdr (assq field nnmail-split-abbrev-alist))
1332                                field)
1333                              "\\):.*\\)\\<\\("
1334                              (if (symbolp value)
1335                                  (cdr (assq value nnmail-split-abbrev-alist))
1336                                value)
1337                              "\\)\\>")))
1338         (push (cons split regexp) nnmail-split-cache)
1339         ;; Now that it's in the cache, just call nnmail-split-it again
1340         ;; on the same split, which will find it immediately in the cache.
1341         (nnmail-split-it split))))))
1342
1343 (defun nnmail-expand-newtext (newtext)
1344   (let ((len (length newtext))
1345         (pos 0)
1346         c expanded beg N did-expand)
1347     (while (< pos len)
1348       (setq beg pos)
1349       (while (and (< pos len)
1350                   (not (= (aref newtext pos) ?\\)))
1351         (setq pos (1+ pos)))
1352       (unless (= beg pos)
1353         (push (substring newtext beg pos) expanded))
1354       (when (< pos len)
1355         ;; We hit a \; expand it.
1356         (setq did-expand t
1357               pos (1+ pos)
1358               c (aref newtext pos))
1359         (if (not (or (= c ?\&)
1360                      (and (>= c ?1)
1361                           (<= c ?9))))
1362             ;; \ followed by some character we don't expand.
1363             (push (char-to-string c) expanded)
1364           ;; \& or \N
1365           (if (= c ?\&)
1366               (setq N 0)
1367             (setq N (- c ?0)))
1368           (when (match-beginning N)
1369             (push (buffer-substring (match-beginning N) (match-end N))
1370                   expanded))))
1371       (setq pos (1+ pos)))
1372     (if did-expand
1373         (apply 'concat (nreverse expanded))
1374       newtext)))
1375
1376 ;; Get a list of spool files to read.
1377 (defun nnmail-get-spool-files (&optional group)
1378   (if (null nnmail-spool-file)
1379       ;; No spool file whatsoever.
1380       nil
1381     (let* ((procmails
1382             ;; If procmail is used to get incoming mail, the files
1383             ;; are stored in this directory.
1384             (and (file-exists-p nnmail-procmail-directory)
1385                  (or (eq nnmail-spool-file 'procmail)
1386                      nnmail-use-procmail)
1387                  (directory-files
1388                   nnmail-procmail-directory
1389                   t (concat (if group (concat "^" (regexp-quote group)) "")
1390                             nnmail-procmail-suffix "$"))))
1391            (p procmails)
1392            (crash (when (and (file-exists-p nnmail-crash-box)
1393                              (> (nnheader-file-size
1394                                  (file-truename nnmail-crash-box))
1395                                 0))
1396                     (list nnmail-crash-box))))
1397       ;; Remove any directories that inadvertently match the procmail
1398       ;; suffix, which might happen if the suffix is "".
1399       (while p
1400         (when (file-directory-p (car p))
1401           (setq procmails (delete (car p) procmails)))
1402         (setq p (cdr p)))
1403       ;; Return the list of spools.
1404       (append
1405        crash
1406        (cond ((and group
1407                    (or (eq nnmail-spool-file 'procmail)
1408                        nnmail-use-procmail)
1409                    procmails)
1410               procmails)
1411              ((and group
1412                    (eq nnmail-spool-file 'procmail))
1413               nil)
1414              ((listp nnmail-spool-file)
1415               (nconc
1416                (apply
1417                 'nconc
1418                 (mapcar
1419                  (lambda (file)
1420                    (if (and (not (string-match "^po:" file))
1421                             (file-directory-p file))
1422                        (nnheader-directory-regular-files file)
1423                      (list file)))
1424                  nnmail-spool-file))
1425                procmails))
1426              ((stringp nnmail-spool-file)
1427               (if (and (not (string-match "^po:" nnmail-spool-file))
1428                        (file-directory-p nnmail-spool-file))
1429                   (nconc
1430                    (nnheader-directory-regular-files nnmail-spool-file)
1431                    procmails)
1432                 (cons nnmail-spool-file procmails)))
1433              ((eq nnmail-spool-file 'pop)
1434               (cons (format "po:%s" (user-login-name)) procmails))
1435              (t
1436               procmails))))))
1437
1438 ;; Activate a backend only if it isn't already activated.
1439 ;; If FORCE, re-read the active file even if the backend is
1440 ;; already activated.
1441 (defun nnmail-activate (backend &optional force)
1442   (nnheader-init-server-buffer)
1443   (let (file timestamp file-time)
1444     (if (or (not (symbol-value (intern (format "%s-group-alist" backend))))
1445             force
1446             (and (setq file (ignore-errors
1447                               (symbol-value (intern (format "%s-active-file"
1448                                                             backend)))))
1449                  (setq file-time (nth 5 (file-attributes file)))
1450                  (or (not
1451                       (setq timestamp
1452                             (condition-case ()
1453                                 (symbol-value (intern
1454                                                (format "%s-active-timestamp"
1455                                                        backend)))
1456                               (error 'none))))
1457                      (not (consp timestamp))
1458                      (equal timestamp '(0 0))
1459                      (> (nth 0 file-time) (nth 0 timestamp))
1460                      (and (= (nth 0 file-time) (nth 0 timestamp))
1461                           (> (nth 1 file-time) (nth 1 timestamp))))))
1462         (save-excursion
1463           (or (eq timestamp 'none)
1464               (set (intern (format "%s-active-timestamp" backend))
1465                    file-time))
1466           (funcall (intern (format "%s-request-list" backend)))))
1467     t))
1468
1469 (defun nnmail-message-id ()
1470   (concat "<" (message-unique-id) "@totally-fudged-out-message-id>"))
1471
1472 ;;;
1473 ;;; nnmail duplicate handling
1474 ;;;
1475
1476 (defvar nnmail-cache-buffer nil)
1477
1478 (defun nnmail-cache-open ()
1479   (if (or (not nnmail-treat-duplicates)
1480           (and nnmail-cache-buffer
1481                (buffer-name nnmail-cache-buffer)))
1482       ()                                ; The buffer is open.
1483     (save-excursion
1484       (set-buffer
1485        (setq nnmail-cache-buffer
1486              (get-buffer-create " *nnmail message-id cache*")))
1487       (buffer-disable-undo (current-buffer))
1488       (when (file-exists-p nnmail-message-id-cache-file)
1489         (nnheader-insert-file-contents nnmail-message-id-cache-file))
1490       (set-buffer-modified-p nil)
1491       (current-buffer))))
1492
1493 (defun nnmail-cache-close ()
1494   (when (and nnmail-cache-buffer
1495              nnmail-treat-duplicates
1496              (buffer-name nnmail-cache-buffer)
1497              (buffer-modified-p nnmail-cache-buffer))
1498     (save-excursion
1499       (set-buffer nnmail-cache-buffer)
1500       ;; Weed out the excess number of Message-IDs.
1501       (goto-char (point-max))
1502       (when (search-backward "\n" nil t nnmail-message-id-cache-length)
1503         (progn
1504           (beginning-of-line)
1505           (delete-region (point-min) (point))))
1506       ;; Save the buffer.
1507       (or (file-exists-p (file-name-directory nnmail-message-id-cache-file))
1508           (make-directory (file-name-directory nnmail-message-id-cache-file)
1509                           t))
1510       (nnmail-write-region (point-min) (point-max)
1511                            nnmail-message-id-cache-file nil 'silent)
1512       (set-buffer-modified-p nil)
1513       (setq nnmail-cache-buffer nil)
1514       (kill-buffer (current-buffer)))))
1515
1516 (defun nnmail-cache-insert (id)
1517   (when nnmail-treat-duplicates
1518     (unless (gnus-buffer-live-p nnmail-cache-buffer)
1519       (nnmail-cache-open))
1520     (save-excursion
1521       (set-buffer nnmail-cache-buffer)
1522       (goto-char (point-max))
1523       (insert id "\n"))))
1524
1525 (defun nnmail-cache-id-exists-p (id)
1526   (when nnmail-treat-duplicates
1527     (save-excursion
1528       (set-buffer nnmail-cache-buffer)
1529       (goto-char (point-max))
1530       (search-backward id nil t))))
1531
1532 (defun nnmail-fetch-field (header)
1533   (save-excursion
1534     (save-restriction
1535       (message-narrow-to-head)
1536       (message-fetch-field header))))
1537
1538 (defun nnmail-check-duplication (message-id func artnum-func)
1539   (run-hooks 'nnmail-prepare-incoming-message-hook)
1540   ;; If this is a duplicate message, then we do not save it.
1541   (let* ((duplication (nnmail-cache-id-exists-p message-id))
1542          (case-fold-search t)
1543          (action (when duplication
1544                    (cond
1545                     ((memq nnmail-treat-duplicates '(warn delete))
1546                      nnmail-treat-duplicates)
1547                     ((nnheader-functionp nnmail-treat-duplicates)
1548                      (funcall nnmail-treat-duplicates message-id))
1549                     (t
1550                      nnmail-treat-duplicates))))
1551          group-art)
1552     ;; Let the backend save the article (or not).
1553     (cond
1554      ((not duplication)
1555       (nnmail-cache-insert message-id)
1556       (funcall func (setq group-art
1557                           (nreverse (nnmail-article-group artnum-func)))))
1558      ((eq action 'delete)
1559       (setq group-art nil))
1560      ((eq action 'warn)
1561       ;; We insert a warning.
1562       (let ((case-fold-search t))
1563         (goto-char (point-min))
1564         (re-search-forward "^message-id[ \t]*:" nil t)
1565         (beginning-of-line)
1566         (insert
1567          "Gnus-Warning: This is a duplicate of message " message-id "\n")
1568         (funcall func (setq group-art
1569                             (nreverse (nnmail-article-group artnum-func))))))
1570      (t
1571       (funcall func (setq group-art
1572                           (nreverse (nnmail-article-group artnum-func))))))
1573     ;; Add the group-art list to the history list.
1574     (if group-art
1575         (push group-art nnmail-split-history)
1576       (delete-region (point-min) (point-max)))))
1577
1578 ;;; Get new mail.
1579
1580 (defun nnmail-get-value (&rest args)
1581   (let ((sym (intern (apply 'format args))))
1582     (when (boundp sym)
1583       (symbol-value sym))))
1584
1585 (defun nnmail-get-new-mail (method exit-func temp
1586                                    &optional group spool-func)
1587   "Read new incoming mail."
1588   (let* ((spools (nnmail-get-spool-files group))
1589          (group-in group)
1590          nnmail-current-spool incoming incomings spool)
1591     (when (and (nnmail-get-value "%s-get-new-mail" method)
1592                nnmail-spool-file)
1593       ;; We first activate all the groups.
1594       (nnmail-activate method)
1595       ;; Allow the user to hook.
1596       (run-hooks 'nnmail-pre-get-new-mail-hook)
1597       ;; Open the message-id cache.
1598       (nnmail-cache-open)
1599       ;; The we go through all the existing spool files and split the
1600       ;; mail from each.
1601       (while spools
1602         (setq spool (pop spools))
1603         ;; We read each spool file if either the spool is a POP-mail
1604         ;; spool, or the file exists.  We can't check for the
1605         ;; existence of POPped mail.
1606         (when (or (string-match "^po:" spool)
1607                   (and (file-exists-p (file-truename spool))
1608                        (> (nnheader-file-size (file-truename spool)) 0)))
1609           (nnheader-message 3 "%s: Reading incoming mail..." method)
1610           (when (and (nnmail-move-inbox spool)
1611                      (file-exists-p nnmail-crash-box))
1612             (setq nnmail-current-spool spool)
1613             ;; There is new mail.  We first find out if all this mail
1614             ;; is supposed to go to some specific group.
1615             (setq group (nnmail-get-split-group spool group-in))
1616             ;; We split the mail
1617             (nnmail-split-incoming
1618              nnmail-crash-box (intern (format "%s-save-mail" method))
1619              spool-func group (intern (format "%s-active-number" method)))
1620             ;; Check whether the inbox is to be moved to the special tmp dir.
1621             (setq incoming
1622                   (nnmail-make-complex-temp-name
1623                    (expand-file-name
1624                     (if nnmail-tmp-directory
1625                         (concat
1626                          (file-name-as-directory nnmail-tmp-directory)
1627                          (file-name-nondirectory
1628                           (concat (file-name-as-directory temp) "Incoming")))
1629                       (concat (file-name-as-directory temp) "Incoming")))))
1630             (unless (file-exists-p (file-name-directory incoming))
1631               (make-directory (file-name-directory incoming) t))
1632             (rename-file nnmail-crash-box incoming t)
1633             (push incoming incomings))))
1634       ;; If we did indeed read any incoming spools, we save all info.
1635       (when incomings
1636         (nnmail-save-active
1637          (nnmail-get-value "%s-group-alist" method)
1638          (nnmail-get-value "%s-active-file" method))
1639         (when exit-func
1640           (funcall exit-func))
1641         (run-hooks 'nnmail-read-incoming-hook)
1642         (nnheader-message 3 "%s: Reading incoming mail...done" method))
1643       ;; Close the message-id cache.
1644       (nnmail-cache-close)
1645       ;; Allow the user to hook.
1646       (run-hooks 'nnmail-post-get-new-mail-hook)
1647       ;; Delete all the temporary files.
1648       (while incomings
1649         (setq incoming (pop incomings))
1650         (and nnmail-delete-incoming
1651              (file-exists-p incoming)
1652              (file-writable-p incoming)
1653              (delete-file incoming))))))
1654
1655 (defun nnmail-expired-article-p (group time force &optional inhibit)
1656   "Say whether an article that is TIME old in GROUP should be expired."
1657   (if force
1658       t
1659     (let ((days (or (and nnmail-expiry-wait-function
1660                          (funcall nnmail-expiry-wait-function group))
1661                     nnmail-expiry-wait)))
1662       (cond ((or (eq days 'never)
1663                  (and (not force)
1664                       inhibit))
1665              ;; This isn't an expirable group.
1666              nil)
1667             ((eq days 'immediate)
1668              ;; We expire all articles on sight.
1669              t)
1670             ((equal time '(0 0))
1671              ;; This is an ange-ftp group, and we don't have any dates.
1672              nil)
1673             ((numberp days)
1674              (setq days (nnmail-days-to-time days))
1675              ;; Compare the time with the current time.
1676              (nnmail-time-less days (nnmail-time-since time)))))))
1677
1678 (defvar nnmail-read-passwd nil)
1679 (defun nnmail-read-passwd (prompt &rest args)
1680   "Read a password using PROMPT.
1681 If ARGS, PROMPT is used as an argument to `format'."
1682   (let ((prompt
1683          (if args
1684              (apply 'format prompt args)
1685            prompt)))
1686     (unless nnmail-read-passwd
1687       (if (load "passwd" t)
1688           (setq nnmail-read-passwd 'read-passwd)
1689         (unless (fboundp 'ange-ftp-read-passwd)
1690           (autoload 'ange-ftp-read-passwd "ange-ftp"))
1691         (setq nnmail-read-passwd 'ange-ftp-read-passwd)))
1692     (funcall nnmail-read-passwd prompt)))
1693
1694 (defun nnmail-check-syntax ()
1695   "Check (and modify) the syntax of the message in the current buffer."
1696   (save-restriction
1697     (message-narrow-to-head)
1698     (let ((case-fold-search t))
1699       (unless (re-search-forward "^Message-ID[ \t]*:" nil t)
1700         (insert "Message-ID: " (nnmail-message-id) "\n")))))
1701
1702 (defun nnmail-write-region (start end filename &optional append visit lockname)
1703   "Do a `write-region', and then set the file modes."
1704   (let ((coding-system-for-write nnmail-file-coding-system)
1705         (pathname-coding-system 'binary))
1706     (write-region start end filename append visit lockname)
1707     (set-file-modes filename nnmail-default-file-modes)))
1708
1709 ;;;
1710 ;;; Status functions
1711 ;;;
1712
1713 (defun nnmail-replace-status (name value)
1714   "Make status NAME and VALUE part of the current status line."
1715   (save-restriction
1716     (message-narrow-to-head)
1717     (let ((status (nnmail-decode-status)))
1718       (setq status (delq (member name status) status))
1719       (when value
1720         (push (cons name value) status))
1721       (message-remove-header "status")
1722       (goto-char (point-max))
1723       (insert "Status: " (nnmail-encode-status status) "\n"))))
1724
1725 (defun nnmail-decode-status ()
1726   "Return a status-value alist from STATUS."
1727   (goto-char (point-min))
1728   (when (re-search-forward "^Status: " nil t)
1729     (let (name value status)
1730       (save-restriction
1731         ;; Narrow to the status.
1732         (narrow-to-region
1733          (point)
1734          (if (re-search-forward "^[^ \t]" nil t)
1735              (1- (point))
1736            (point-max)))
1737         ;; Go through all elements and add them to the list.
1738         (goto-char (point-min))
1739         (while (re-search-forward "[^ \t=]+" nil t)
1740           (setq name (match-string 0))
1741           (if (not (= (following-char) ?=))
1742               ;; Implied "yes".
1743               (setq value "yes")
1744             (forward-char 1)
1745             (if (not (= (following-char) ?\"))
1746                 (if (not (looking-at "[^ \t]"))
1747                     ;; Implied "no".
1748                     (setq value "no")
1749                   ;; Unquoted value.
1750                   (setq value (match-string 0))
1751                   (goto-char (match-end 0)))
1752               ;; Quoted value.
1753               (setq value (read (current-buffer)))))
1754           (push (cons name value) status)))
1755       status)))
1756
1757 (defun nnmail-encode-status (status)
1758   "Return a status string from STATUS."
1759   (mapconcat
1760    (lambda (elem)
1761      (concat
1762       (car elem) "="
1763       (if (string-match "[ \t]" (cdr elem))
1764           (prin1-to-string (cdr elem))
1765         (cdr elem))))
1766    status " "))
1767
1768 (defun nnmail-split-history ()
1769   "Generate an overview of where the last mail split put articles."
1770   (interactive)
1771   (unless nnmail-split-history
1772     (error "No current split history"))
1773   (with-output-to-temp-buffer "*nnmail split history*"
1774     (let ((history nnmail-split-history)
1775           elem)
1776       (while (setq elem (pop history))
1777         (princ (mapconcat (lambda (ga)
1778                             (concat (car ga) ":" (int-to-string (cdr ga))))
1779                           elem
1780                           ", "))
1781         (princ "\n")))))
1782
1783 (defun nnmail-purge-split-history (group)
1784   "Remove all instances of GROUP from `nnmail-split-history'."
1785   (let ((history nnmail-split-history))
1786     (while history
1787       (setcar history (gnus-delete-if (lambda (e) (string= (car e) group))
1788                                       (car history)))
1789       (pop history))
1790     (setq nnmail-split-history (delq nil nnmail-split-history))))
1791
1792 (defun nnmail-new-mail-p (group)
1793   "Say whether GROUP has new mail."
1794   (let ((his nnmail-split-history)
1795         found)
1796     (while his
1797       (when (assoc group (pop his))
1798         (setq found t
1799               his nil)))
1800     found))
1801
1802 (eval-and-compile
1803   (autoload 'pop3-movemail "pop3"))
1804
1805 (defun nnmail-pop3-movemail (inbox crashbox)
1806   "Function to move mail from INBOX on a pop3 server to file CRASHBOX."
1807   (let ((pop3-maildrop
1808          (substring inbox (match-end (string-match "^po:" inbox)))))
1809     (pop3-movemail crashbox)))
1810
1811 (defun nnmail-within-headers-p ()
1812   "Check to see if point is within the headers of a unix mail message.
1813 Doesn't change point."
1814   (let ((pos (point)))
1815     (save-excursion
1816       (and (nnmail-search-unix-mail-delim-backward)
1817            (not (search-forward "\n\n" pos t))))))
1818
1819 (run-hooks 'nnmail-load-hook)
1820
1821 (provide 'nnmail)
1822
1823 ;;; nnmail.el ends here