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