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