*** 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                        ;; `nnmail-split-methods' is a function, so we
1046                        ;; just call this function here and use the
1047                        ;; result.
1048                        (or (funcall nnmail-split-methods)
1049                            '("bogus"))
1050                      (error
1051                       (message
1052                        "Error in `nnmail-split-methods'; using `bogus' mail group")
1053                       (sit-for 1)
1054                       '("bogus")))))
1055               ;; The article may be "cross-posted" to `junk'.  What
1056               ;; to do?  Just remove the `junk' spec.  Don't really
1057               ;; see anything else to do...
1058               (let (elem)
1059                 (while (setq elem (assq 'junk split))
1060                   (setq split (delq elem split))))
1061               (when split
1062                 (setq group-art
1063                       (mapcar
1064                        (lambda (group) (cons group (funcall func group)))
1065                        split))))
1066           ;; Go through the split methods to find a match.
1067           (while (and methods (or nnmail-crosspost (not group-art)))
1068             (goto-char (point-max))
1069             (setq method (pop methods))
1070             (if (or methods
1071                     (not (equal "" (nth 1 method))))
1072                 (when (and
1073                        (ignore-errors
1074                          (if (stringp (nth 1 method))
1075                              (re-search-backward (cadr method) nil t)
1076                            ;; Function to say whether this is a match.
1077                            (funcall (nth 1 method) (car method))))
1078                        ;; Don't enter the article into the same
1079                        ;; group twice.
1080                        (not (assoc (car method) group-art)))
1081                   (push (cons (car method) (funcall func (car method)))
1082                         group-art))
1083               ;; This is the final group, which is used as a
1084               ;; catch-all.
1085               (unless group-art
1086                 (setq group-art
1087                       (list (cons (car method)
1088                                   (funcall func (car method)))))))))
1089         ;; See whether the split methods returned `junk'.
1090         (if (equal group-art '(junk))
1091             nil
1092           ;; The article may be "cross-posted" to `junk'.  What
1093           ;; to do?  Just remove the `junk' spec.  Don't really
1094           ;; see anything else to do...
1095           (let (elem)
1096             (while (setq elem (assq 'junk group-art))
1097               (setq group-art (delq elem group-art)))
1098             (nreverse group-art)))))))
1099
1100 (defun nnmail-insert-lines ()
1101   "Insert how many lines there are in the body of the mail.
1102 Return the number of characters in the body."
1103   (let (lines chars)
1104     (save-excursion
1105       (goto-char (point-min))
1106       (when (search-forward "\n\n" nil t)
1107         (setq chars (- (point-max) (point)))
1108         (setq lines (count-lines (point) (point-max)))
1109         (forward-char -1)
1110         (save-excursion
1111           (when (re-search-backward "^Lines: " nil t)
1112             (delete-region (point) (progn (forward-line 1) (point)))))
1113         (beginning-of-line)
1114         (insert (format "Lines: %d\n" (max lines 0)))
1115         chars))))
1116
1117 (defun nnmail-insert-xref (group-alist)
1118   "Insert an Xref line based on the (group . article) alist."
1119   (save-excursion
1120     (goto-char (point-min))
1121     (when (search-forward "\n\n" nil t)
1122       (forward-char -1)
1123       (when (re-search-backward "^Xref: " nil t)
1124         (delete-region (match-beginning 0)
1125                        (progn (forward-line 1) (point))))
1126       (insert (format "Xref: %s" (system-name)))
1127       (while group-alist
1128         (insert (format " %s:%d" (caar group-alist) (cdar group-alist)))
1129         (setq group-alist (cdr group-alist)))
1130       (insert "\n"))))
1131
1132 ;;; Message washing functions
1133
1134 (defun nnmail-remove-leading-whitespace ()
1135   "Remove excessive whitespace from all headers."
1136   (goto-char (point-min))
1137   (while (re-search-forward "^\\([^ :]+: \\) +" nil t)
1138     (replace-match "\\1" t)))
1139
1140 (defun nnmail-remove-list-identifiers ()
1141   "Remove list identifiers from Subject headers."
1142   (let ((regexp (if (stringp nnmail-list-identifiers) nnmail-list-identifiers
1143                   (mapconcat 'identity nnmail-list-identifiers "\\|"))))
1144     (when regexp
1145       (goto-char (point-min))
1146       (when (re-search-forward
1147              (concat "^Subject: +\\(Re: +\\)?\\(" regexp "\\) *")
1148              nil t)
1149         (delete-region (match-beginning 2) (match-end 0))))))
1150
1151 (defun nnmail-remove-tabs ()
1152   "Translate TAB characters into SPACE characters."
1153   (subst-char-in-region (point-min) (point-max) ?\t ?  t))
1154
1155 ;;; Utility functions
1156
1157 ;; Written by byer@mv.us.adobe.com (Scott Byer).
1158 (defun nnmail-make-complex-temp-name (prefix)
1159   (let ((newname (make-temp-name prefix))
1160         (newprefix prefix))
1161     (while (file-exists-p newname)
1162       (setq newprefix (concat newprefix "x"))
1163       (setq newname (make-temp-name newprefix)))
1164     newname))
1165
1166 ;; Written by Per Abrahamsen <amanda@iesd.auc.dk>.
1167
1168 (defun nnmail-split-fancy ()
1169   "Fancy splitting method.
1170 See the documentation for the variable `nnmail-split-fancy' for documentation."
1171   (let ((syntab (syntax-table)))
1172     (unwind-protect
1173         (progn
1174           (set-syntax-table nnmail-split-fancy-syntax-table)
1175           (nnmail-split-it nnmail-split-fancy))
1176       (set-syntax-table syntab))))
1177
1178 (defvar nnmail-split-cache nil)
1179 ;; Alist of split expressions their equivalent regexps.
1180
1181 (defun nnmail-split-it (split)
1182   ;; Return a list of groups matching SPLIT.
1183   (cond
1184    ;; nil split
1185    ((null split)
1186     nil)
1187
1188    ;; A group name.  Do the \& and \N subs into the string.
1189    ((stringp split)
1190     (list (nnmail-expand-newtext split)))
1191
1192    ;; Junk the message.
1193    ((eq split 'junk)
1194     (list 'junk))
1195
1196    ;; Builtin & operation.
1197    ((eq (car split) '&)
1198     (apply 'nconc (mapcar 'nnmail-split-it (cdr split))))
1199
1200    ;; Builtin | operation.
1201    ((eq (car split) '|)
1202     (let (done)
1203       (while (and (not done) (cdr split))
1204         (setq split (cdr split)
1205               done (nnmail-split-it (car split))))
1206       done))
1207
1208    ;; Builtin : operation.
1209    ((eq (car split) ':)
1210     (nnmail-split-it (eval (cdr split))))
1211
1212    ;; Check the cache for the regexp for this split.
1213    ;; FIX FIX FIX could avoid calling assq twice here
1214    ((assq split nnmail-split-cache)
1215     (goto-char (point-max))
1216     ;; FIX FIX FIX problem with re-search-backward is that if you have
1217     ;; a split: (from "foo-\\(bar\\|baz\\)@gnus.org "mail.foo.\\1")
1218     ;; and someone mails a message with 'To: foo-bar@gnus.org' and
1219     ;; 'CC: foo-baz@gnus.org', we'll pick 'mail.foo.baz' as the group
1220     ;; if the cc line is a later header, even though the other choice
1221     ;; is probably better.  Also, this routine won't do a crosspost
1222     ;; when there are two different matches.
1223     ;; I guess you could just make this more determined, and it could
1224     ;; look for still more matches prior to this one, and recurse
1225     ;; on each of the multiple matches hit.  Of course, then you'd
1226     ;; want to make sure that nnmail-article-group or nnmail-split-fancy
1227     ;; removed duplicates, since there might be more of those.
1228     ;; I guess we could also remove duplicates in the & split case, since
1229     ;; that's the only thing that can introduce them.
1230     (when (re-search-backward (cdr (assq split nnmail-split-cache)) nil t)
1231       ;; Someone might want to do a \N sub on this match, so get the
1232       ;; correct match positions.
1233       (goto-char (match-end 0))
1234       (let ((value (nth 1 split)))
1235         (re-search-backward (if (symbolp value)
1236                                 (cdr (assq value nnmail-split-abbrev-alist))
1237                               value)
1238                             (match-end 1)))
1239       (nnmail-split-it (nth 2 split))))
1240
1241    ;; Not in cache, compute a regexp for the field/value pair.
1242    (t
1243     (let* ((field (nth 0 split))
1244            (value (nth 1 split))
1245            (regexp (concat "^\\(\\("
1246                            (if (symbolp field)
1247                                (cdr (assq field nnmail-split-abbrev-alist))
1248                              field)
1249                            "\\):.*\\)\\<\\("
1250                            (if (symbolp value)
1251                                (cdr (assq value nnmail-split-abbrev-alist))
1252                              value)
1253                            "\\)\\>")))
1254       (push (cons split regexp) nnmail-split-cache)
1255       ;; Now that it's in the cache, just call nnmail-split-it again
1256       ;; on the same split, which will find it immediately in the cache.
1257       (nnmail-split-it split)))))
1258
1259 (defun nnmail-expand-newtext (newtext)
1260   (let ((len (length newtext))
1261         (pos 0)
1262         c expanded beg N did-expand)
1263     (while (< pos len)
1264       (setq beg pos)
1265       (while (and (< pos len)
1266                   (not (= (aref newtext pos) ?\\)))
1267         (setq pos (1+ pos)))
1268       (unless (= beg pos)
1269         (push (substring newtext beg pos) expanded))
1270       (when (< pos len)
1271         ;; we hit a \, expand it.
1272         (setq did-expand t)
1273         (setq pos (1+ pos))
1274         (setq c (aref newtext pos))
1275         (if (not (or (= c ?\&)
1276                      (and (>= c ?1)
1277                           (<= c ?9))))
1278             ;; \ followed by some character we don't expand
1279             (push (char-to-string c) expanded)
1280           ;; \& or \N
1281           (if (= c ?\&)
1282               (setq N 0)
1283             (setq N (- c ?0)))
1284           (when (match-beginning N)
1285             (push (buffer-substring (match-beginning N) (match-end N))
1286                   expanded))))
1287       (setq pos (1+ pos)))
1288     (if did-expand
1289         (apply 'concat (nreverse expanded))
1290       newtext)))
1291
1292 ;; Get a list of spool files to read.
1293 (defun nnmail-get-spool-files (&optional group)
1294   (if (null nnmail-spool-file)
1295       ;; No spool file whatsoever.
1296       nil
1297     (let* ((procmails
1298             ;; If procmail is used to get incoming mail, the files
1299             ;; are stored in this directory.
1300             (and (file-exists-p nnmail-procmail-directory)
1301                  (or (eq nnmail-spool-file 'procmail)
1302                      nnmail-use-procmail)
1303                  (directory-files
1304                   nnmail-procmail-directory
1305                   t (concat (if group (concat "^" group) "")
1306                             nnmail-procmail-suffix "$"))))
1307            (p procmails)
1308            (crash (when (and (file-exists-p nnmail-crash-box)
1309                              (> (nnheader-file-size
1310                                  (file-truename nnmail-crash-box))
1311                                 0))
1312                     (list nnmail-crash-box))))
1313       ;; Remove any directories that inadvertently match the procmail
1314       ;; suffix, which might happen if the suffix is "".
1315       (while p
1316         (when (file-directory-p (car p))
1317           (setq procmails (delete (car p) procmails)))
1318         (setq p (cdr p)))
1319       ;; Return the list of spools.
1320       (append
1321        crash
1322        (cond ((and group
1323                    (or (eq nnmail-spool-file 'procmail)
1324                        nnmail-use-procmail)
1325                    procmails)
1326               procmails)
1327              ((and group
1328                    (eq nnmail-spool-file 'procmail))
1329               nil)
1330              ((listp nnmail-spool-file)
1331               (nconc
1332                (apply
1333                 'nconc
1334                 (mapcar
1335                  (lambda (file)
1336                    (if (and (not (string-match "^po:" file))
1337                             (file-directory-p file))
1338                        (nnheader-directory-regular-files file)
1339                      (list file)))
1340                  nnmail-spool-file))
1341                procmails))
1342              ((stringp nnmail-spool-file)
1343               (if (and (not (string-match "^po:" nnmail-spool-file))
1344                        (file-directory-p nnmail-spool-file))
1345                   (nconc
1346                    (nnheader-directory-regular-files nnmail-spool-file)
1347                    procmails)
1348                 (cons nnmail-spool-file procmails)))
1349              ((eq nnmail-spool-file 'pop)
1350               (cons (format "po:%s" (user-login-name)) procmails))
1351              (t
1352               procmails))))))
1353
1354 ;; Activate a backend only if it isn't already activated.
1355 ;; If FORCE, re-read the active file even if the backend is
1356 ;; already activated.
1357 (defun nnmail-activate (backend &optional force)
1358   (let (file timestamp file-time)
1359     (if (or (not (symbol-value (intern (format "%s-group-alist" backend))))
1360             force
1361             (and (setq file (ignore-errors
1362                               (symbol-value (intern (format "%s-active-file"
1363                                                             backend)))))
1364                  (setq file-time (nth 5 (file-attributes file)))
1365                  (or (not
1366                       (setq timestamp
1367                             (condition-case ()
1368                                 (symbol-value (intern
1369                                                (format "%s-active-timestamp"
1370                                                        backend)))
1371                               (error 'none))))
1372                      (not (consp timestamp))
1373                      (equal timestamp '(0 0))
1374                      (> (nth 0 file-time) (nth 0 timestamp))
1375                      (and (= (nth 0 file-time) (nth 0 timestamp))
1376                           (> (nth 1 file-time) (nth 1 timestamp))))))
1377         (save-excursion
1378           (or (eq timestamp 'none)
1379               (set (intern (format "%s-active-timestamp" backend))
1380                    file-time))
1381           (funcall (intern (format "%s-request-list" backend)))))
1382     t))
1383
1384 (defun nnmail-message-id ()
1385   (concat "<" (message-unique-id) "@totally-fudged-out-message-id>"))
1386
1387 ;;;
1388 ;;; nnmail duplicate handling
1389 ;;;
1390
1391 (defvar nnmail-cache-buffer nil)
1392
1393 (defun nnmail-cache-open ()
1394   (if (or (not nnmail-treat-duplicates)
1395           (and nnmail-cache-buffer
1396                (buffer-name nnmail-cache-buffer)))
1397       ()                                ; The buffer is open.
1398     (save-excursion
1399       (set-buffer
1400        (setq nnmail-cache-buffer
1401              (get-buffer-create " *nnmail message-id cache*")))
1402       (buffer-disable-undo (current-buffer))
1403       (when (file-exists-p nnmail-message-id-cache-file)
1404         (nnheader-insert-file-contents nnmail-message-id-cache-file))
1405       (set-buffer-modified-p nil)
1406       (current-buffer))))
1407
1408 (defun nnmail-cache-close ()
1409   (when (and nnmail-cache-buffer
1410              nnmail-treat-duplicates
1411              (buffer-name nnmail-cache-buffer)
1412              (buffer-modified-p nnmail-cache-buffer))
1413     (save-excursion
1414       (set-buffer nnmail-cache-buffer)
1415       ;; Weed out the excess number of Message-IDs.
1416       (goto-char (point-max))
1417       (when (search-backward "\n" nil t nnmail-message-id-cache-length)
1418         (progn
1419           (beginning-of-line)
1420           (delete-region (point-min) (point))))
1421       ;; Save the buffer.
1422       (or (file-exists-p (file-name-directory nnmail-message-id-cache-file))
1423           (make-directory (file-name-directory nnmail-message-id-cache-file)
1424                           t))
1425       (nnmail-write-region (point-min) (point-max)
1426                            nnmail-message-id-cache-file nil 'silent)
1427       (set-buffer-modified-p nil)
1428       (setq nnmail-cache-buffer nil)
1429       (kill-buffer (current-buffer)))))
1430
1431 (defun nnmail-cache-insert (id)
1432   (when nnmail-treat-duplicates
1433     (unless (gnus-buffer-live-p nnmail-cache-buffer)
1434       (nnmail-cache-open))
1435     (save-excursion
1436       (set-buffer nnmail-cache-buffer)
1437       (goto-char (point-max))
1438       (insert id "\n"))))
1439
1440 (defun nnmail-cache-id-exists-p (id)
1441   (when nnmail-treat-duplicates
1442     (save-excursion
1443       (set-buffer nnmail-cache-buffer)
1444       (goto-char (point-max))
1445       (search-backward id nil t))))
1446
1447 (defun nnmail-fetch-field (header)
1448   (save-excursion
1449     (save-restriction
1450       (message-narrow-to-head)
1451       (message-fetch-field header))))
1452
1453 (defun nnmail-check-duplication (message-id func artnum-func)
1454   (run-hooks 'nnmail-prepare-incoming-message-hook)
1455   ;; If this is a duplicate message, then we do not save it.
1456   (let* ((duplication (nnmail-cache-id-exists-p message-id))
1457          (case-fold-search t)
1458          (action (when duplication
1459                    (cond
1460                     ((memq nnmail-treat-duplicates '(warn delete))
1461                      nnmail-treat-duplicates)
1462                     ((nnheader-functionp nnmail-treat-duplicates)
1463                      (funcall nnmail-treat-duplicates message-id))
1464                     (t
1465                      nnmail-treat-duplicates))))
1466          group-art)
1467     ;; Let the backend save the article (or not).
1468     (cond
1469      ((not duplication)
1470       (nnmail-cache-insert message-id)
1471       (funcall func (setq group-art
1472                           (nreverse (nnmail-article-group artnum-func)))))
1473      ((eq action 'delete)
1474       (setq group-art nil))
1475      ((eq action 'warn)
1476       ;; We insert a warning.
1477       (let ((case-fold-search t))
1478         (goto-char (point-min))
1479         (re-search-forward "^message-id[ \t]*:" nil t)
1480         (beginning-of-line)
1481         (insert
1482          "Gnus-Warning: This is a duplicate of message " message-id "\n")
1483         (funcall func (setq group-art
1484                             (nreverse (nnmail-article-group artnum-func))))))
1485      (t
1486       (funcall func (setq group-art
1487                           (nreverse (nnmail-article-group artnum-func))))))
1488     ;; Add the group-art list to the history list.
1489     (if group-art
1490         (push group-art nnmail-split-history)
1491       (delete-region (point-min) (point-max)))))
1492
1493 ;;; Get new mail.
1494
1495 (defun nnmail-get-value (&rest args)
1496   (let ((sym (intern (apply 'format args))))
1497     (when (boundp sym)
1498       (symbol-value sym))))
1499
1500 (defun nnmail-get-new-mail (method exit-func temp
1501                                    &optional group spool-func)
1502   "Read new incoming mail."
1503   ;; Nix out the previous split history.
1504   (unless group
1505     (setq nnmail-split-history nil))
1506   (let* ((spools (nnmail-get-spool-files group))
1507          (group-in group)
1508          incoming incomings spool)
1509     (when (and (nnmail-get-value "%s-get-new-mail" method)
1510                nnmail-spool-file)
1511       ;; We first activate all the groups.
1512       (nnmail-activate method)
1513       ;; Allow the user to hook.
1514       (run-hooks 'nnmail-pre-get-new-mail-hook)
1515       ;; Open the message-id cache.
1516       (nnmail-cache-open)
1517       ;; The we go through all the existing spool files and split the
1518       ;; mail from each.
1519       (while spools
1520         (setq spool (pop spools))
1521         ;; We read each spool file if either the spool is a POP-mail
1522         ;; spool, or the file exists.  We can't check for the
1523         ;; existence of POPped mail.
1524         (when (or (string-match "^po:" spool)
1525                   (and (file-exists-p (file-truename spool))
1526                        (> (nnheader-file-size (file-truename spool)) 0)))
1527           (nnheader-message 3 "%s: Reading incoming mail..." method)
1528           (when (and (nnmail-move-inbox spool)
1529                      (file-exists-p nnmail-crash-box))
1530             ;; There is new mail.  We first find out if all this mail
1531             ;; is supposed to go to some specific group.
1532             (setq group (nnmail-get-split-group spool group-in))
1533             ;; We split the mail
1534             (nnmail-split-incoming
1535              nnmail-crash-box (intern (format "%s-save-mail" method))
1536              spool-func group (intern (format "%s-active-number" method)))
1537             ;; Check whether the inbox is to be moved to the special tmp dir.
1538             (setq incoming
1539                   (nnmail-make-complex-temp-name
1540                    (expand-file-name
1541                     (if nnmail-tmp-directory
1542                         (concat
1543                          (file-name-as-directory nnmail-tmp-directory)
1544                          (file-name-nondirectory
1545                           (concat (file-name-as-directory temp) "Incoming")))
1546                       (concat (file-name-as-directory temp) "Incoming")))))
1547             (rename-file nnmail-crash-box incoming t)
1548             (push incoming incomings))))
1549       ;; If we did indeed read any incoming spools, we save all info.
1550       (when incomings
1551         (nnmail-save-active
1552          (nnmail-get-value "%s-group-alist" method)
1553          (nnmail-get-value "%s-active-file" method))
1554         (when exit-func
1555           (funcall exit-func))
1556         (run-hooks 'nnmail-read-incoming-hook)
1557         (nnheader-message 3 "%s: Reading incoming mail...done" method))
1558       ;; Close the message-id cache.
1559       (nnmail-cache-close)
1560       ;; Allow the user to hook.
1561       (run-hooks 'nnmail-post-get-new-mail-hook)
1562       ;; Delete all the temporary files.
1563       (while incomings
1564         (setq incoming (pop incomings))
1565         (and nnmail-delete-incoming
1566              (file-exists-p incoming)
1567              (file-writable-p incoming)
1568              (delete-file incoming))))))
1569
1570 (defun nnmail-expired-article-p (group time force &optional inhibit)
1571   "Say whether an article that is TIME old in GROUP should be expired."
1572   (if force
1573       t
1574     (let ((days (or (and nnmail-expiry-wait-function
1575                          (funcall nnmail-expiry-wait-function group))
1576                     nnmail-expiry-wait)))
1577       (cond ((or (eq days 'never)
1578                  (and (not force)
1579                       inhibit))
1580              ;; This isn't an expirable group.
1581              nil)
1582             ((eq days 'immediate)
1583              ;; We expire all articles on sight.
1584              t)
1585             ((equal time '(0 0))
1586              ;; This is an ange-ftp group, and we don't have any dates.
1587              nil)
1588             ((numberp days)
1589              (setq days (nnmail-days-to-time days))
1590              ;; Compare the time with the current time.
1591              (nnmail-time-less days (nnmail-time-since time)))))))
1592
1593 (defvar nnmail-read-passwd nil)
1594 (defun nnmail-read-passwd (prompt &rest args)
1595   "Read a password using PROMPT.
1596 If ARGS, PROMPT is used as an argument to `format'."
1597   (let ((prompt
1598          (if args
1599              (apply 'format prompt args)
1600            prompt)))
1601     (unless nnmail-read-passwd
1602       (if (load "passwd" t)
1603           (setq nnmail-read-passwd 'read-passwd)
1604         (unless (fboundp 'ange-ftp-read-passwd)
1605           (autoload 'ange-ftp-read-passwd "ange-ftp"))
1606         (setq nnmail-read-passwd 'ange-ftp-read-passwd)))
1607     (funcall nnmail-read-passwd prompt)))
1608
1609 (defun nnmail-check-syntax ()
1610   "Check (and modify) the syntax of the message in the current buffer."
1611   (save-restriction
1612     (message-narrow-to-head)
1613     (let ((case-fold-search t))
1614       (unless (re-search-forward "^Message-ID[ \t]*:" nil t)
1615         (insert "Message-ID: " (nnmail-message-id) "\n")))))
1616
1617 (defun nnmail-write-region (start end filename &optional append visit lockname)
1618   "Do a `write-region', and then set the file modes."
1619   (write-region start end filename append visit lockname)
1620   (set-file-modes filename nnmail-default-file-modes))
1621
1622 ;;;
1623 ;;; Status functions
1624 ;;;
1625
1626 (defun nnmail-replace-status (name value)
1627   "Make status NAME and VALUE part of the current status line."
1628   (save-restriction
1629     (message-narrow-to-head)
1630     (let ((status (nnmail-decode-status)))
1631       (setq status (delq (member name status) status))
1632       (when value
1633         (push (cons name value) status))
1634       (message-remove-header "status")
1635       (goto-char (point-max))
1636       (insert "Status: " (nnmail-encode-status status) "\n"))))
1637
1638 (defun nnmail-decode-status ()
1639   "Return a status-value alist from STATUS."
1640   (goto-char (point-min))
1641   (when (re-search-forward "^Status: " nil t)
1642     (let (name value status)
1643       (save-restriction
1644         ;; Narrow to the status.
1645         (narrow-to-region
1646          (point)
1647          (if (re-search-forward "^[^ \t]" nil t)
1648              (1- (point))
1649            (point-max)))
1650         ;; Go through all elements and add them to the list.
1651         (goto-char (point-min))
1652         (while (re-search-forward "[^ \t=]+" nil t)
1653           (setq name (match-string 0))
1654           (if (not (= (following-char) ?=))
1655               ;; Implied "yes".
1656               (setq value "yes")
1657             (forward-char 1)
1658             (if (not (= (following-char) ?\"))
1659                 (if (not (looking-at "[^ \t]"))
1660                     ;; Implied "no".
1661                     (setq value "no")
1662                   ;; Unquoted value.
1663                   (setq value (match-string 0))
1664                   (goto-char (match-end 0)))
1665               ;; Quoted value.
1666               (setq value (read (current-buffer)))))
1667           (push (cons name value) status)))
1668       status)))
1669
1670 (defun nnmail-encode-status (status)
1671   "Return a status string from STATUS."
1672   (mapconcat
1673    (lambda (elem)
1674      (concat
1675       (car elem) "="
1676       (if (string-match "[ \t]" (cdr elem))
1677           (prin1-to-string (cdr elem))
1678         (cdr elem))))
1679    status " "))
1680
1681 (defun nnmail-split-history ()
1682   "Generate an overview of where the last mail split put articles."
1683   (interactive)
1684   (unless nnmail-split-history
1685     (error "No current split history"))
1686   (with-output-to-temp-buffer "*nnmail split history*"
1687     (let ((history nnmail-split-history)
1688           elem)
1689       (while (setq elem (pop history))
1690         (princ (mapconcat (lambda (ga)
1691                             (concat (car ga) ":" (int-to-string (cdr ga))))
1692                           elem
1693                           ", "))
1694         (princ "\n")))))
1695
1696 (defun nnmail-new-mail-p (group)
1697   "Say whether GROUP has new mail."
1698   (let ((his nnmail-split-history)
1699         found)
1700     (while his
1701       (when (assoc group (pop his))
1702         (setq found t
1703               his nil)))
1704     found))
1705
1706 (eval-and-compile
1707   (autoload 'pop3-movemail "pop3"))
1708
1709 (defun nnmail-pop3-movemail (inbox crashbox)
1710   "Function to move mail from INBOX on a pop3 server to file CRASHBOX."
1711   (let ((pop3-maildrop
1712          (substring inbox (match-end (string-match "^po:" inbox)))))
1713     (pop3-movemail crashbox)))
1714
1715 (run-hooks 'nnmail-load-hook)
1716
1717 (provide 'nnmail)
1718
1719 ;;; nnmail.el ends here