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