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