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