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