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