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