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