Revision: emacs@sv.gnu.org/gnus--devo--0--patch-25
[gnus] / lisp / nnmail.el
1 ;;; nnmail.el --- mail support functions for the Gnus mail backends
2
3 ;; Copyright (C) 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003,
4 ;;   2004, 2005, 2006 Free Software Foundation, Inc.
5
6 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
7 ;; Keywords: news, mail
8
9 ;; This file is part of GNU Emacs.
10
11 ;; GNU Emacs is free software; you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation; either version 2, or (at your option)
14 ;; any later version.
15
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19 ;; GNU General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
23 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
24 ;; Boston, MA 02110-1301, USA.
25
26 ;;; Commentary:
27
28 ;;; Code:
29
30 (eval-when-compile (require 'cl))
31
32 (require 'gnus)                         ; for macro gnus-kill-buffer, at least
33 (require 'nnheader)
34 (require 'message)
35 (require 'gnus-util)
36 (require 'mail-source)
37 (require 'mm-util)
38
39 (eval-and-compile
40   (autoload 'gnus-add-buffer "gnus")
41   (autoload 'gnus-kill-buffer "gnus"))
42
43 (defgroup nnmail nil
44   "Reading mail with Gnus."
45   :group 'gnus)
46
47 (defgroup nnmail-retrieve nil
48   "Retrieving new mail."
49   :group 'nnmail)
50
51 (defgroup nnmail-prepare nil
52   "Preparing (or mangling) new mail after retrieval."
53   :group 'nnmail)
54
55 (defgroup nnmail-duplicate nil
56   "Handling of duplicate mail messages."
57   :group 'nnmail)
58
59 (defgroup nnmail-split nil
60   "Organizing the incoming mail in folders."
61   :group 'nnmail)
62
63 (defgroup nnmail-files nil
64   "Mail files."
65   :group 'gnus-files
66   :group 'nnmail)
67
68 (defgroup nnmail-expire nil
69   "Expiring old mail."
70   :group 'nnmail)
71
72 (defgroup nnmail-procmail nil
73   "Interfacing with procmail and other mail agents."
74   :group 'nnmail)
75
76 (defgroup nnmail-various nil
77   "Various mail options."
78   :group 'nnmail)
79
80 (defcustom nnmail-split-methods '(("mail.misc" ""))
81   "*Incoming mail will be split according to this variable.
82
83 If you'd like, for instance, one mail group for mail from the
84 \"4ad-l\" mailing list, one group for junk mail and one for everything
85 else, you could do something like this:
86
87  (setq nnmail-split-methods
88        '((\"mail.4ad\" \"From:.*4ad\")
89          (\"mail.junk\" \"From:.*Lars\\\\|Subject:.*buy\")
90          (\"mail.misc\" \"\")))
91
92 As you can see, this variable is a list of lists, where the first
93 element in each \"rule\" is the name of the group (which, by the way,
94 does not have to be called anything beginning with \"mail\",
95 \"yonka.zow\" is a fine, fine name), and the second is a regexp that
96 nnmail will try to match on the header to find a fit.
97
98 The second element can also be a function.  In that case, it will be
99 called narrowed to the headers with the first element of the rule as
100 the argument.  It should return a non-nil value if it thinks that the
101 mail belongs in that group.
102
103 The last element should always have \"\" as the regexp.
104
105 This variable can also have a function as its value."
106   :group 'nnmail-split
107   :type '(choice (repeat :tag "Alist" (group (string :tag "Name")
108                                              (choice regexp function)))
109                  (function-item nnmail-split-fancy)
110                  (function :tag "Other")))
111
112 ;; Suggested by Erik Selberg <speed@cs.washington.edu>.
113 (defcustom nnmail-crosspost t
114   "If non-nil, do crossposting if several split methods match the mail.
115 If nil, the first match found will be used."
116   :group 'nnmail-split
117   :type 'boolean)
118
119 (defcustom nnmail-split-fancy-with-parent-ignore-groups nil
120   "Regexp that matches group names to be ignored when applying `nnmail-split-fancy-with-parent'.
121 This can also be a list of regexps."
122   :version "22.1"
123   :group 'nnmail-split
124   :type '(choice (const :tag "none" nil)
125                  (regexp :value ".*")
126                  (repeat :value (".*") regexp)))
127
128 (defcustom nnmail-cache-ignore-groups nil
129   "Regexp that matches group names to be ignored when inserting message ids into the cache (`nnmail-cache-insert').
130 This can also be a list of regexps."
131   :version "22.1"
132   :group 'nnmail-split
133   :type '(choice (const :tag "none" nil)
134                  (regexp :value ".*")
135                  (repeat :value (".*") regexp)))
136
137 ;; Added by gord@enci.ucalgary.ca (Gordon Matzigkeit).
138 (defcustom nnmail-keep-last-article nil
139   "If non-nil, nnmail will never delete/move a group's last article.
140 It can be marked expirable, so it will be deleted when it is no longer last.
141
142 You may need to set this variable if other programs are putting
143 new mail into folder numbers that Gnus has marked as expired."
144   :group 'nnmail-procmail
145   :group 'nnmail-various
146   :type 'boolean)
147
148 (defcustom nnmail-use-long-file-names nil
149   "If non-nil the mail backends will use long file and directory names.
150 If nil, groups like \"mail.misc\" will end up in directories like
151 \"mail/misc/\"."
152   :group 'nnmail-files
153   :type 'boolean)
154
155 (defcustom nnmail-default-file-modes 384
156   "Set the mode bits of all new mail files to this integer."
157   :group 'nnmail-files
158   :type 'integer)
159
160 (defcustom nnmail-expiry-wait 7
161   "*Expirable articles that are older than this will be expired.
162 This variable can either be a number (which will be interpreted as a
163 number of days) -- this doesn't have to be an integer.  This variable
164 can also be `immediate' and `never'."
165   :group 'nnmail-expire
166   :type '(choice (const immediate)
167                  (number :tag "days")
168                  (const never)))
169
170 (defcustom nnmail-expiry-wait-function nil
171   "Variable that holds function to specify how old articles should be before they are expired.
172 The function will be called with the name of the group that the expiry
173 is to be performed in, and it should return an integer that says how
174 many days an article can be stored before it is considered \"old\".
175 It can also return the values `never' and `immediate'.
176
177 Eg.:
178
179 \(setq nnmail-expiry-wait-function
180       (lambda (newsgroup)
181         (cond ((string-match \"private\" newsgroup) 31)
182               ((string-match \"junk\" newsgroup) 1)
183               ((string-match \"important\" newsgroup) 'never)
184               (t 7))))"
185   :group 'nnmail-expire
186   :type '(choice (const :tag "nnmail-expiry-wait" nil)
187                  (function :format "%v" nnmail-)))
188
189 (defcustom nnmail-expiry-target 'delete
190   "*Variable that says where expired messages should end up.
191 The default value is `delete' (which says to delete the messages),
192 but it can also be a string or a function.  If it is a string, expired
193 messages end up in that group.  If it is a function, the function is
194 called in a buffer narrowed to the message in question.  The function
195 receives one argument, the name of the group the message comes from.
196 The return value should be `delete' or a group name (a string)."
197   :version "21.1"
198   :group 'nnmail-expire
199   :type '(choice (const delete)
200                  (function :format "%v" nnmail-)
201                  string))
202
203 (defcustom nnmail-fancy-expiry-targets nil
204   "Determine expiry target based on articles using fancy techniques.
205
206 This is a list of (\"HEADER\" \"REGEXP\" \"TARGET\") entries.  If
207 `nnmail-expiry-target' is set to the function
208 `nnmail-fancy-expiry-target' and HEADER of the article matches REGEXP,
209 the message will be expired to a group determined by invoking
210 `format-time-string' with TARGET used as the format string and the
211 time extracted from the articles' Date header (if missing the current
212 time is used).
213
214 In the special cases that HEADER is the symbol `to-from', the regexp
215 will try to match against both the From and the To header.
216
217 Example:
218
219 \(setq nnmail-fancy-expiry-targets
220       '((to-from \"boss\" \"nnfolder:Work\")
221         (\"Subject\" \"IMPORTANT\" \"nnfolder:IMPORTANT.%Y.%b\")
222         (\"from\" \".*\" \"nnfolder:Archive-%Y\")))
223
224 In this case, articles containing the string \"boss\" in the To or the
225 From header will be expired to the group \"nnfolder:Work\";
226 articles containing the sting \"IMPORTANT\" in the Subject header will
227 be expired to the group \"nnfolder:IMPORTANT.YYYY.MMM\"; and
228 everything else will be expired to \"nnfolder:Archive-YYYY\"."
229   :version "22.1"
230   :group 'nnmail-expire
231   :type '(repeat (list (choice :tag "Match against"
232                                (string :tag "Header")
233                                (const to-from))
234                        regexp
235                        (string :tag "Target group format string"))))
236
237 (defcustom nnmail-cache-accepted-message-ids nil
238   "If non-nil, put Message-IDs of Gcc'd articles into the duplicate cache.
239 If non-nil, also update the cache when copy or move articles."
240   :group 'nnmail
241   :type 'boolean)
242
243 (defcustom nnmail-spool-file '((file))
244   "*Where the mail backends will look for incoming mail.
245 This variable is a list of mail source specifiers.
246 This variable is obsolete; `mail-sources' should be used instead."
247   :group 'nnmail-files
248   :type 'sexp)
249
250 (defcustom nnmail-resplit-incoming nil
251   "*If non-nil, re-split incoming procmail sorted mail."
252   :group 'nnmail-procmail
253   :type 'boolean)
254
255 (defcustom nnmail-scan-directory-mail-source-once nil
256   "*If non-nil, scan all incoming procmail sorted mails once.
257 It scans low-level sorted spools even when not required."
258   :version "21.1"
259   :group 'nnmail-procmail
260   :type 'boolean)
261
262 (defcustom nnmail-delete-file-function 'delete-file
263   "Function called to delete files in some mail backends."
264   :group 'nnmail-files
265   :type 'function)
266
267 (defcustom nnmail-crosspost-link-function
268   (if (string-match "windows-nt\\|emx" (symbol-name system-type))
269       'copy-file
270     'add-name-to-file)
271   "*Function called to create a copy of a file.
272 This is `add-name-to-file' by default, which means that crossposts
273 will use hard links.  If your file system doesn't allow hard
274 links, you could set this variable to `copy-file' instead."
275   :group 'nnmail-files
276   :type '(radio (function-item add-name-to-file)
277                 (function-item copy-file)
278                 (function :tag "Other")))
279
280 (defcustom nnmail-read-incoming-hook
281   (if (eq system-type 'windows-nt)
282       '(nnheader-ms-strip-cr)
283     nil)
284   "*Hook that will be run after the incoming mail has been transferred.
285 The incoming mail is moved from the specified spool file (which normally is
286 something like \"/usr/spool/mail/$user\") to the user's home
287 directory.  This hook is called after the incoming mail box has been
288 emptied, and can be used to call any mail box programs you have
289 running (\"xwatch\", etc.)
290
291 Eg.
292
293 \(add-hook 'nnmail-read-incoming-hook
294           (lambda ()
295             (call-process \"/local/bin/mailsend\" nil nil nil
296                           \"read\" nnmail-spool-file)))
297
298 If you have xwatch running, this will alert it that mail has been
299 read.
300
301 If you use `display-time', you could use something like this:
302
303 \(add-hook 'nnmail-read-incoming-hook
304           (lambda ()
305             ;; Update the displayed time, since that will clear out
306             ;; the flag that says you have mail.
307             (when (eq (process-status \"display-time\") 'run)
308               (display-time-filter display-time-process \"\"))))"
309   :group 'nnmail-prepare
310   :type 'hook)
311
312 (defcustom nnmail-prepare-incoming-hook nil
313   "Hook called before treating incoming mail.
314 The hook is run in a buffer with all the new, incoming mail."
315   :group 'nnmail-prepare
316   :type 'hook)
317
318 (defcustom nnmail-prepare-incoming-header-hook nil
319   "Hook called narrowed to the headers of each message.
320 This can be used to remove excessive spaces (and stuff like
321 that) from the headers before splitting and saving the messages."
322   :group 'nnmail-prepare
323   :type 'hook)
324
325 (defcustom nnmail-prepare-incoming-message-hook nil
326   "Hook called narrowed to each message."
327   :group 'nnmail-prepare
328   :type 'hook)
329
330 (defcustom nnmail-list-identifiers nil
331   "Regexp that matches list identifiers to be removed.
332 This can also be a list of regexps."
333   :group 'nnmail-prepare
334   :type '(choice (const :tag "none" nil)
335                  (regexp :value ".*")
336                  (repeat :value (".*") regexp)))
337
338 (defcustom nnmail-pre-get-new-mail-hook nil
339   "Hook called just before starting to handle new incoming mail."
340   :group 'nnmail-retrieve
341   :type 'hook)
342
343 (defcustom nnmail-post-get-new-mail-hook nil
344   "Hook called just after finishing handling new incoming mail."
345   :group 'nnmail-retrieve
346   :type 'hook)
347
348 (defcustom nnmail-split-hook nil
349   "Hook called before deciding where to split an article.
350 The functions in this hook are free to modify the buffer
351 contents in any way they choose -- the buffer contents are
352 discarded after running the split process."
353   :group 'nnmail-split
354   :type 'hook)
355
356 (defcustom nnmail-spool-hook nil
357   "*A hook called when a new article is spooled."
358   :version "22.1"
359   :group 'nnmail
360   :type 'hook)
361
362 (defcustom nnmail-large-newsgroup 50
363   "*The number of articles which indicates a large newsgroup or nil.
364 If the number of articles is greater than the value, verbose
365 messages will be shown to indicate the current status."
366   :group 'nnmail-various
367   :type '(choice (const :tag "infinite" nil)
368                  (number :tag "count")))
369
370 (define-widget 'nnmail-lazy 'default
371   "Base widget for recursive datastructures.
372
373 This is copy of the `lazy' widget in Emacs 22.1 provided for compatibility."
374   :format "%{%t%}: %v"
375   :convert-widget 'widget-value-convert-widget
376   :value-create (lambda (widget)
377                   (let ((value (widget-get widget :value))
378                         (type (widget-get widget :type)))
379                     (widget-put widget :children
380                                 (list (widget-create-child-value
381                                        widget (widget-convert type) value)))))
382   :value-delete 'widget-children-value-delete
383   :value-get (lambda (widget)
384                (widget-value (car (widget-get widget :children))))
385   :value-inline (lambda (widget)
386                   (widget-apply (car (widget-get widget :children))
387                                 :value-inline))
388   :default-get (lambda (widget)
389                  (widget-default-get
390                   (widget-convert (widget-get widget :type))))
391   :match (lambda (widget value)
392            (widget-apply (widget-convert (widget-get widget :type))
393                          :match value))
394   :validate (lambda (widget)
395               (widget-apply (car (widget-get widget :children)) :validate)))
396
397 (define-widget 'nnmail-split-fancy 'nnmail-lazy
398   "Widget for customizing splits in the variable of the same name."
399   :tag "Split"
400   :type '(menu-choice :value (any ".*value.*" "misc")
401                       :tag "Type"
402                       (string :tag "Destination")
403                       (list :tag "Use first match (|)" :value (|)
404                             (const :format "" |)
405                             (editable-list :inline t nnmail-split-fancy))
406                       (list :tag "Use all matches (&)" :value (&)
407                             (const :format "" &)
408                             (editable-list :inline t nnmail-split-fancy))
409                       (list :tag "Function with fixed arguments (:)"
410                             :value (:)
411                             (const :format "" :value :)
412                             function
413                             (editable-list :inline t (sexp :tag "Arg"))
414                             )
415                       (list :tag "Function with split arguments (!)"
416                             :value (!)
417                             (const :format "" !)
418                             function
419                             (editable-list :inline t nnmail-split-fancy))
420                       (list :tag "Field match"
421                             (choice :tag "Field"
422                                     regexp symbol)
423                             (choice :tag "Match"
424                                     regexp
425                                     (symbol :value mail))
426                             (repeat :inline t
427                                     :tag "Restrictions"
428                                     (group :inline t
429                                            (const :format "" -)
430                                            regexp))
431                             nnmail-split-fancy)
432                       (const :tag "Junk (delete mail)" junk)))
433
434 (defcustom nnmail-split-fancy "mail.misc"
435   "Incoming mail can be split according to this fancy variable.
436 To enable this, set `nnmail-split-methods' to `nnmail-split-fancy'.
437
438 The format of this variable is SPLIT, where SPLIT can be one of
439 the following:
440
441 GROUP: Mail will be stored in GROUP (a string).
442
443 \(FIELD VALUE [- RESTRICT [- RESTRICT [...]]] SPLIT): If the message
444   field FIELD (a regexp) contains VALUE (a regexp), store the messages
445   as specified by SPLIT.  If RESTRICT (a regexp) matches some string
446   after FIELD and before the end of the matched VALUE, return nil,
447   otherwise process SPLIT.  Multiple RESTRICTs add up, further
448   restricting the possibility of processing SPLIT.
449
450 \(| SPLIT...): Process each SPLIT expression until one of them matches.
451   A SPLIT expression is said to match if it will cause the mail
452   message to be stored in one or more groups.
453
454 \(& SPLIT...): Process each SPLIT expression.
455
456 \(: FUNCTION optional args): Call FUNCTION with the optional args, in
457   the buffer containing the message headers.  The return value FUNCTION
458   should be a split, which is then recursively processed.
459
460 \(! FUNCTION SPLIT): Call FUNCTION with the result of SPLIT.  The
461   return value FUNCTION should be a split, which is then recursively
462   processed.
463
464 junk: Mail will be deleted.  Use with care!  Do not submerge in water!
465   Example:
466   (setq nnmail-split-fancy
467         '(| (\"Subject\" \"MAKE MONEY FAST\" junk)
468             ...other.rules.omitted...))
469
470 FIELD must match a complete field name.  VALUE must match a complete
471 word according to the `nnmail-split-fancy-syntax-table' syntax table.
472 You can use \".*\" in the regexps to match partial field names or words.
473
474 FIELD and VALUE can also be Lisp symbols, in that case they are expanded
475 as specified in `nnmail-split-abbrev-alist'.
476
477 GROUP can contain \\& and \\N which will substitute from matching
478 \\(\\) patterns in the previous VALUE.
479
480 Example:
481
482 \(setq nnmail-split-methods 'nnmail-split-fancy
483       nnmail-split-fancy
484       ;; Messages from the mailer daemon are not crossposted to any of
485       ;; the ordinary groups.  Warnings are put in a separate group
486       ;; from real errors.
487       '(| (\"from\" mail (| (\"subject\" \"warn.*\" \"mail.warning\")
488                           \"mail.misc\"))
489           ;; Non-error messages are crossposted to all relevant
490           ;; groups, but we don't crosspost between the group for the
491           ;; (ding) list and the group for other (ding) related mail.
492           (& (| (any \"ding@ifi\\\\.uio\\\\.no\" \"ding.list\")
493                 (\"subject\" \"ding\" \"ding.misc\"))
494              ;; Other mailing lists...
495              (any \"procmail@informatik\\\\.rwth-aachen\\\\.de\" \"procmail.list\")
496              (any \"SmartList@informatik\\\\.rwth-aachen\\\\.de\" \"SmartList.list\")
497              ;; Both lists below have the same suffix, so prevent
498              ;; cross-posting to mkpkg.list of messages posted only to
499              ;; the bugs- list, but allow cross-posting when the
500              ;; message was really cross-posted.
501              (any \"bugs-mypackage@somewhere\" \"mypkg.bugs\")
502              (any \"mypackage@somewhere\" - \"bugs-mypackage\" \"mypkg.list\")
503              ;;
504              ;; People...
505              (any \"larsi@ifi\\\\.uio\\\\.no\" \"people.Lars Magne Ingebrigtsen\"))
506           ;; Unmatched mail goes to the catch all group.
507           \"misc.misc\"))"
508   :group 'nnmail-split
509   :type 'nnmail-split-fancy)
510
511 (defcustom nnmail-split-abbrev-alist
512   '((any . "from\\|to\\|cc\\|sender\\|apparently-to\\|resent-from\\|resent-to\\|resent-cc")
513     (mail . "mailer-daemon\\|postmaster\\|uucp")
514     (to . "to\\|cc\\|apparently-to\\|resent-to\\|resent-cc")
515     (from . "from\\|sender\\|resent-from")
516     (nato . "to\\|cc\\|resent-to\\|resent-cc")
517     (naany . "from\\|to\\|cc\\|sender\\|resent-from\\|resent-to\\|resent-cc"))
518   "*Alist of abbreviations allowed in `nnmail-split-fancy'."
519   :group 'nnmail-split
520   :type '(repeat (cons :format "%v" symbol regexp)))
521
522 (defcustom nnmail-message-id-cache-length 1000
523   "*The approximate number of Message-IDs nnmail will keep in its cache.
524 If this variable is nil, no checking on duplicate messages will be
525 performed."
526   :group 'nnmail-duplicate
527   :type '(choice (const :tag "disable" nil)
528                  (integer :format "%v")))
529
530 (defcustom nnmail-message-id-cache-file "~/.nnmail-cache"
531   "*The file name of the nnmail Message-ID cache."
532   :group 'nnmail-duplicate
533   :group 'nnmail-files
534   :type 'file)
535
536 (defcustom nnmail-treat-duplicates 'warn
537   "*If non-nil, nnmail keep a cache of Message-IDs to discover mail duplicates.
538 Three values are valid: nil, which means that nnmail is not to keep a
539 Message-ID cache; `warn', which means that nnmail should insert extra
540 headers to warn the user about the duplication (this is the default);
541 and `delete', which means that nnmail will delete duplicated mails.
542
543 This variable can also be a function.  It will be called from a buffer
544 narrowed to the article in question with the Message-ID as a
545 parameter.  It should return nil, `warn' or `delete'."
546   :group 'nnmail-duplicate
547   :type '(choice (const :tag "off" nil)
548                  (const warn)
549                  (const delete)))
550
551 (defcustom nnmail-extra-headers '(To Newsgroups)
552   "*Extra headers to parse."
553   :version "21.1"
554   :group 'nnmail
555   :type '(repeat symbol))
556
557 (defcustom nnmail-split-header-length-limit 2048
558   "Header lines longer than this limit are excluded from the split function."
559   :version "21.1"
560   :group 'nnmail
561   :type 'integer)
562
563 (defcustom nnmail-mail-splitting-charset nil
564   "Default charset to be used when splitting incoming mail."
565   :version "22.1"
566   :group 'nnmail
567   :type 'symbol)
568
569 (defcustom nnmail-mail-splitting-decodes nil
570   "Whether the nnmail splitting functionality should MIME decode headers."
571   :version "22.1"
572   :group 'nnmail
573   :type 'boolean)
574
575 (defcustom nnmail-split-fancy-match-partial-words nil
576   "Whether to match partial words when fancy splitting.
577 Normally, regexes given in `nnmail-split-fancy' are implicitly surrounded
578 by \"\\=\\<...\\>\".  If this variable is true, they are not implicitly\
579  surrounded
580 by anything."
581   :version "22.1"
582   :group 'nnmail
583   :type 'boolean)
584
585 (defcustom nnmail-split-lowercase-expanded t
586   "Whether to lowercase expanded entries (i.e. \\N) when splitting mails.
587 This avoids the creation of multiple groups when users send to an address
588 using different case (i.e. mailing-list@domain vs Mailing-List@Domain)."
589   :version "22.1"
590   :group 'nnmail
591   :type 'boolean)
592
593 ;;; Internal variables.
594
595 (defvar nnmail-article-buffer " *nnmail incoming*"
596   "The buffer used for splitting incoming mails.")
597
598 (defvar nnmail-split-history nil
599   "List of group/article elements that say where the previous split put messages.")
600
601 (defvar nnmail-split-fancy-syntax-table
602   (let ((table (make-syntax-table)))
603     ;; support the %-hack
604     (modify-syntax-entry ?\% "." table)
605     table)
606   "Syntax table used by `nnmail-split-fancy'.")
607
608 (defvar nnmail-prepare-save-mail-hook nil
609   "Hook called before saving mail.")
610
611 (defvar nnmail-split-tracing nil)
612 (defvar nnmail-split-trace nil)
613
614 \f
615
616 (defun nnmail-request-post (&optional server)
617   (mail-send-and-exit nil))
618
619 (defvar nnmail-file-coding-system 'raw-text
620   "Coding system used in nnmail.")
621
622 (defvar nnmail-incoming-coding-system
623   mm-text-coding-system
624   "Coding system used in reading inbox")
625
626 (defvar nnmail-pathname-coding-system nil
627   "*Coding system for file name.")
628
629 (defun nnmail-find-file (file)
630   "Insert FILE in server buffer safely."
631   (set-buffer nntp-server-buffer)
632   (delete-region (point-min) (point-max))
633   (let ((format-alist nil)
634         (after-insert-file-functions nil))
635     (condition-case ()
636         (let ((coding-system-for-read nnmail-file-coding-system)
637               (auto-mode-alist (mm-auto-mode-alist))
638               (file-name-coding-system nnmail-pathname-coding-system))
639           (insert-file-contents file)
640           t)
641       (file-error nil))))
642
643 (defun nnmail-group-pathname (group dir &optional file)
644   "Make file name for GROUP."
645   (concat
646    (let ((dir (file-name-as-directory (expand-file-name dir))))
647      (setq group (nnheader-replace-duplicate-chars-in-string
648                   (nnheader-replace-chars-in-string group ?/ ?_)
649                   ?. ?_))
650      (setq group (nnheader-translate-file-chars group))
651      ;; If this directory exists, we use it directly.
652      (file-name-as-directory
653       (if (or nnmail-use-long-file-names
654               (file-directory-p (concat dir group)))
655           (expand-file-name group dir)
656         ;; If not, we translate dots into slashes.
657         (expand-file-name
658          (mm-encode-coding-string
659           (nnheader-replace-chars-in-string group ?. ?/)
660           nnmail-pathname-coding-system)
661          dir))))
662    (or file "")))
663
664 (defun nnmail-get-active ()
665   "Returns an assoc of group names and active ranges.
666 nn*-request-list should have been called before calling this function."
667   ;; Go through all groups from the active list.
668   (save-excursion
669     (set-buffer nntp-server-buffer)
670     (nnmail-parse-active)))
671
672 (defun nnmail-parse-active ()
673   "Parse the active file in the current buffer and return an alist."
674   (goto-char (point-min))
675   (unless (re-search-forward "[\\\"]" nil t)
676     (goto-char (point-max))
677     (while (re-search-backward "[][';?()#]" nil t)
678       (insert ?\\)))
679   (goto-char (point-min))
680   (let ((buffer (current-buffer))
681         group-assoc group max min)
682     (while (not (eobp))
683       (condition-case err
684           (progn
685             (narrow-to-region (point) (point-at-eol))
686             (setq group (read buffer))
687             (unless (stringp group)
688               (setq group (symbol-name group)))
689             (if (and (numberp (setq max (read buffer)))
690                      (numberp (setq min (read buffer))))
691                 (push (list group (cons min max))
692                       group-assoc)))
693         (error nil))
694       (widen)
695       (forward-line 1))
696     group-assoc))
697
698 (defvar nnmail-active-file-coding-system 'raw-text
699   "*Coding system for active file.")
700
701 (defun nnmail-save-active (group-assoc file-name)
702   "Save GROUP-ASSOC in ACTIVE-FILE."
703   (let ((coding-system-for-write nnmail-active-file-coding-system))
704     (when file-name
705       (with-temp-file file-name
706         (nnmail-generate-active group-assoc)))))
707
708 (defun nnmail-generate-active (alist)
709   "Generate an active file from group-alist ALIST."
710   (erase-buffer)
711   (let (group)
712     (while (setq group (pop alist))
713       (insert (format "%S %d %d y\n" (intern (car group)) (cdadr group)
714                       (caadr group))))
715     (goto-char (point-max))
716     (while (search-backward "\\." nil t)
717       (delete-char 1))))
718
719 (defun nnmail-get-split-group (file source)
720   "Find out whether this FILE is to be split into GROUP only.
721 If SOURCE is a directory spec, try to return the group name component."
722   (if (eq (car source) 'directory)
723       (let ((file (file-name-nondirectory file)))
724         (mail-source-bind (directory source)
725           (if (string-match (concat (regexp-quote suffix) "$") file)
726               (substring file 0 (match-beginning 0))
727             nil)))
728     nil))
729
730 (defun nnmail-process-babyl-mail-format (func artnum-func)
731   (let ((case-fold-search t)
732         (count 0)
733         start message-id content-length do-search end)
734     (while (not (eobp))
735       (goto-char (point-min))
736       (re-search-forward
737        "\f\n0, *unseen,+\n\\(\\*\\*\\* EOOH \\*\\*\\*\n\\)?" nil t)
738       (goto-char (match-end 0))
739       (delete-region (match-beginning 0) (match-end 0))
740       (narrow-to-region
741        (setq start (point))
742        (progn
743          ;; Skip all the headers in case there are more "From "s...
744          (or (search-forward "\n\n" nil t)
745              (search-forward-regexp "^[^:]*\\( .*\\|\\)$" nil t)
746              (search-forward "\1f\f"))
747          (point)))
748       ;; Unquote the ">From " line, if any.
749       (goto-char (point-min))
750       (when (looking-at ">From ")
751         (replace-match "X-From-Line: ") )
752       (run-hooks 'nnmail-prepare-incoming-header-hook)
753       (goto-char (point-max))
754       ;; Find the Message-ID header.
755       (save-excursion
756         (if (re-search-backward
757              "^Message-ID[ \t]*:[ \n\t]*\\(<[^>]*>\\)" nil t)
758             (setq message-id (buffer-substring (match-beginning 1)
759                                                (match-end 1)))
760           ;; There is no Message-ID here, so we create one.
761           (save-excursion
762             (when (re-search-backward "^Message-ID[ \t]*:" nil t)
763               (beginning-of-line)
764               (insert "Original-")))
765           (forward-line -1)
766           (insert "Message-ID: " (setq message-id (nnmail-message-id))
767                   "\n")))
768       ;; Look for a Content-Length header.
769       (if (not (save-excursion
770                  (and (re-search-backward
771                        "^Content-Length:[ \t]*\\([0-9]+\\)" start t)
772                       (setq content-length (string-to-number
773                                             (buffer-substring
774                                              (match-beginning 1)
775                                              (match-end 1))))
776                       ;; We destroy the header, since none of
777                       ;; the backends ever use it, and we do not
778                       ;; want to confuse other mailers by having
779                       ;; a (possibly) faulty header.
780                       (progn (insert "X-") t))))
781           (setq do-search t)
782         (widen)
783         (if (or (= (+ (point) content-length) (point-max))
784                 (save-excursion
785                   (goto-char (+ (point) content-length))
786                   (looking-at "\1f")))
787             (progn
788               (goto-char (+ (point) content-length))
789               (setq do-search nil))
790           (setq do-search t)))
791       (widen)
792       ;; Go to the beginning of the next article - or to the end
793       ;; of the buffer.
794       (when do-search
795         (if (re-search-forward "^\1f" nil t)
796             (goto-char (match-beginning 0))
797           (goto-char (1- (point-max)))))
798       (delete-char 1)                   ; delete ^_
799       (save-excursion
800         (save-restriction
801           (narrow-to-region start (point))
802           (goto-char (point-min))
803           (nnmail-check-duplication message-id func artnum-func)
804           (incf count)
805           (setq end (point-max))))
806       (goto-char end))
807     count))
808
809 (defsubst nnmail-search-unix-mail-delim ()
810   "Put point at the beginning of the next Unix mbox message."
811   ;; Algorithm used to find the next article in the
812   ;; brain-dead Unix mbox format:
813   ;;
814   ;; 1) Search for "^From ".
815   ;; 2) If we find it, then see whether the previous
816   ;;    line is blank and the next line looks like a header.
817   ;; Then it's possible that this is a mail delim, and we use it.
818   (let ((case-fold-search nil)
819         found)
820     (while (not found)
821       (if (not (re-search-forward "^From " nil t))
822           (setq found 'no)
823         (save-excursion
824           (beginning-of-line)
825           (when (and (or (bobp)
826                          (save-excursion
827                            (forward-line -1)
828                            (eq (char-after) ?\n)))
829                      (save-excursion
830                        (forward-line 1)
831                        (while (looking-at ">From \\|From ")
832                          (forward-line 1))
833                        (looking-at "[^ \n\t:]+[ \n\t]*:")))
834             (setq found 'yes)))))
835     (beginning-of-line)
836     (eq found 'yes)))
837
838 (defun nnmail-search-unix-mail-delim-backward ()
839   "Put point at the beginning of the current Unix mbox message."
840   ;; Algorithm used to find the next article in the
841   ;; brain-dead Unix mbox format:
842   ;;
843   ;; 1) Search for "^From ".
844   ;; 2) If we find it, then see whether the previous
845   ;;    line is blank and the next line looks like a header.
846   ;; Then it's possible that this is a mail delim, and we use it.
847   (let ((case-fold-search nil)
848         found)
849     (while (not found)
850       (if (not (re-search-backward "^From " nil t))
851           (setq found 'no)
852         (save-excursion
853           (beginning-of-line)
854           (when (and (or (bobp)
855                          (save-excursion
856                            (forward-line -1)
857                            (eq (char-after) ?\n)))
858                      (save-excursion
859                        (forward-line 1)
860                        (while (looking-at ">From \\|From ")
861                          (forward-line 1))
862                        (looking-at "[^ \n\t:]+[ \n\t]*:")))
863             (setq found 'yes)))))
864     (beginning-of-line)
865     (eq found 'yes)))
866
867 (defun nnmail-process-unix-mail-format (func artnum-func)
868   (let ((case-fold-search t)
869         (count 0)
870         start message-id content-length end skip head-end)
871     (goto-char (point-min))
872     (if (not (and (re-search-forward "^From " nil t)
873                   (goto-char (match-beginning 0))))
874         ;; Possibly wrong format?
875         (error "Error, unknown mail format! (Possibly corrupted %s `%s'.)"
876                (if (buffer-file-name) "file" "buffer")
877                (or (buffer-file-name) (buffer-name)))
878       ;; Carry on until the bitter end.
879       (while (not (eobp))
880         (setq start (point)
881               end nil)
882         ;; Find the end of the head.
883         (narrow-to-region
884          start
885          (if (search-forward "\n\n" nil t)
886              (1- (point))
887            ;; This will never happen, but just to be on the safe side --
888            ;; if there is no head-body delimiter, we search a bit manually.
889            (while (and (looking-at "From \\|[^ \t]+:")
890                        (not (eobp)))
891              (forward-line 1))
892            (point)))
893         ;; Find the Message-ID header.
894         (goto-char (point-min))
895         (if (re-search-forward "^Message-ID[ \t]*:[ \n\t]*\\(<[^>]+>\\)" nil t)
896             (setq message-id (match-string 1))
897           (save-excursion
898             (when (re-search-forward "^Message-ID[ \t]*:" nil t)
899               (beginning-of-line)
900               (insert "Original-")))
901           ;; There is no Message-ID here, so we create one.
902           (forward-line 1)
903           (insert "Message-ID: " (setq message-id (nnmail-message-id)) "\n"))
904         ;; Look for a Content-Length header.
905         (goto-char (point-min))
906         (if (not (re-search-forward
907                   "^Content-Length:[ \t]*\\([0-9]+\\)" nil t))
908             (setq content-length nil)
909           (setq content-length (string-to-number (match-string 1)))
910           ;; We destroy the header, since none of the backends ever
911           ;; use it, and we do not want to confuse other mailers by
912           ;; having a (possibly) faulty header.
913           (beginning-of-line)
914           (insert "X-"))
915         (run-hooks 'nnmail-prepare-incoming-header-hook)
916         ;; Find the end of this article.
917         (goto-char (point-max))
918         (widen)
919         (setq head-end (point))
920         ;; We try the Content-Length value.  The idea: skip over the header
921         ;; separator, then check what happens content-length bytes into the
922         ;; message body.  This should be either the end of the buffer, the
923         ;; message separator or a blank line followed by the separator.
924         ;; The blank line should probably be deleted.  If neither of the
925         ;; three is met, the content-length header is probably invalid.
926         (when content-length
927           (forward-line 1)
928           (setq skip (+ (point) content-length))
929           (goto-char skip)
930           (cond ((or (= skip (point-max))
931                      (= (1+ skip) (point-max)))
932                  (setq end (point-max)))
933                 ((looking-at "From ")
934                  (setq end skip))
935                 ((looking-at "[ \t]*\n\\(From \\)")
936                  (setq end (match-beginning 1)))
937                 (t (setq end nil))))
938         (if end
939             (goto-char end)
940           ;; No Content-Length, so we find the beginning of the next
941           ;; article or the end of the buffer.
942           (goto-char head-end)
943           (or (nnmail-search-unix-mail-delim)
944               (goto-char (point-max))))
945         ;; Allow the backend to save the article.
946         (save-excursion
947           (save-restriction
948             (narrow-to-region start (point))
949             (goto-char (point-min))
950             (incf count)
951             (nnmail-check-duplication message-id func artnum-func)
952             (setq end (point-max))))
953         (goto-char end)))
954     count))
955
956 (defun nnmail-process-mmdf-mail-format (func artnum-func)
957   (let ((delim "^\^A\^A\^A\^A$")
958         (case-fold-search t)
959         (count 0)
960         start message-id end)
961     (goto-char (point-min))
962     (if (not (and (re-search-forward delim nil t)
963                   (forward-line 1)))
964         ;; Possibly wrong format?
965         (error "Error, unknown mail format! (Possibly corrupted.)")
966       ;; Carry on until the bitter end.
967       (while (not (eobp))
968         (setq start (point))
969         ;; Find the end of the head.
970         (narrow-to-region
971          start
972          (if (search-forward "\n\n" nil t)
973              (1- (point))
974            ;; This will never happen, but just to be on the safe side --
975            ;; if there is no head-body delimiter, we search a bit manually.
976            (while (and (looking-at "From \\|[^ \t]+:")
977                        (not (eobp)))
978              (forward-line 1))
979            (point)))
980         ;; Find the Message-ID header.
981         (goto-char (point-min))
982         (if (re-search-forward "^Message-ID[ \t]*:[ \n\t]*\\(<[^>]+>\\)" nil t)
983             (setq message-id (match-string 1))
984           ;; There is no Message-ID here, so we create one.
985           (save-excursion
986             (when (re-search-backward "^Message-ID[ \t]*:" nil t)
987               (beginning-of-line)
988               (insert "Original-")))
989           (forward-line 1)
990           (insert "Message-ID: " (setq message-id (nnmail-message-id)) "\n"))
991         (run-hooks 'nnmail-prepare-incoming-header-hook)
992         ;; Find the end of this article.
993         (goto-char (point-max))
994         (widen)
995         (if (re-search-forward delim nil t)
996             (beginning-of-line)
997           (goto-char (point-max)))
998         ;; Allow the backend to save the article.
999         (save-excursion
1000           (save-restriction
1001             (narrow-to-region start (point))
1002             (goto-char (point-min))
1003             (incf count)
1004             (nnmail-check-duplication message-id func artnum-func)
1005             (setq end (point-max))))
1006         (goto-char end)
1007         (forward-line 2)))
1008     count))
1009
1010 (defun nnmail-process-maildir-mail-format (func artnum-func)
1011   ;; In a maildir, every file contains exactly one mail.
1012   (let ((case-fold-search t)
1013         message-id)
1014     (goto-char (point-min))
1015     ;; Find the end of the head.
1016     (narrow-to-region
1017      (point-min)
1018      (if (search-forward "\n\n" nil t)
1019          (1- (point))
1020        ;; This will never happen, but just to be on the safe side --
1021        ;; if there is no head-body delimiter, we search a bit manually.
1022        (while (and (looking-at "From \\|[^ \t]+:")
1023                    (not (eobp)))
1024          (forward-line 1))
1025        (point)))
1026     ;; Find the Message-ID header.
1027     (goto-char (point-min))
1028     (if (re-search-forward "^Message-ID:[ \t]*\\(<[^>]+>\\)" nil t)
1029         (setq message-id (match-string 1))
1030       ;; There is no Message-ID here, so we create one.
1031       (save-excursion
1032         (when (re-search-backward "^Message-ID[ \t]*:" nil t)
1033           (beginning-of-line)
1034           (insert "Original-")))
1035       (forward-line 1)
1036       (insert "Message-ID: " (setq message-id (nnmail-message-id)) "\n"))
1037     (run-hooks 'nnmail-prepare-incoming-header-hook)
1038     ;; Allow the backend to save the article.
1039     (widen)
1040     (save-excursion
1041       (goto-char (point-min))
1042       (nnmail-check-duplication message-id func artnum-func))
1043     1))
1044
1045 (defun nnmail-split-incoming (incoming func &optional exit-func
1046                                        group artnum-func)
1047   "Go through the entire INCOMING file and pick out each individual mail.
1048 FUNC will be called with the buffer narrowed to each mail."
1049   (let ( ;; If this is a group-specific split, we bind the split
1050         ;; methods to just this group.
1051         (nnmail-split-methods (if (and group
1052                                        (not nnmail-resplit-incoming))
1053                                   (list (list group ""))
1054                                 nnmail-split-methods)))
1055     (save-excursion
1056       ;; Insert the incoming file.
1057       (set-buffer (get-buffer-create nnmail-article-buffer))
1058       (erase-buffer)
1059       (let ((coding-system-for-read nnmail-incoming-coding-system))
1060         (mm-insert-file-contents incoming))
1061       (prog1
1062           (if (zerop (buffer-size))
1063               0
1064             (goto-char (point-min))
1065             (save-excursion (run-hooks 'nnmail-prepare-incoming-hook))
1066             ;; Handle both babyl, MMDF and unix mail formats, since
1067             ;; movemail will use the former when fetching from a
1068             ;; mailbox, the latter when fetching from a file.
1069             (cond ((or (looking-at "\^L")
1070                        (looking-at "BABYL OPTIONS:"))
1071                    (nnmail-process-babyl-mail-format func artnum-func))
1072                   ((looking-at "\^A\^A\^A\^A")
1073                    (nnmail-process-mmdf-mail-format func artnum-func))
1074                   ((looking-at "Return-Path:")
1075                    (nnmail-process-maildir-mail-format func artnum-func))
1076                   (t
1077                    (nnmail-process-unix-mail-format func artnum-func))))
1078         (when exit-func
1079           (funcall exit-func))
1080         (kill-buffer (current-buffer))))))
1081
1082 (defun nnmail-article-group (func &optional trace)
1083   "Look at the headers and return an alist of groups that match.
1084 FUNC will be called with the group name to determine the article number."
1085   (let ((methods (or nnmail-split-methods '(("bogus" ""))))
1086         (obuf (current-buffer))
1087         group-art method grp)
1088     (if (and (sequencep methods)
1089              (= (length methods) 1))
1090         ;; If there is only just one group to put everything in, we
1091         ;; just return a list with just this one method in.
1092         (setq group-art
1093               (list (cons (caar methods) (funcall func (caar methods)))))
1094       ;; We do actual comparison.
1095       (save-excursion
1096         ;; Copy the article into the work buffer.
1097         (set-buffer nntp-server-buffer)
1098         (erase-buffer)
1099         (insert-buffer-substring obuf)
1100         ;; Narrow to headers.
1101         (narrow-to-region
1102          (goto-char (point-min))
1103          (if (search-forward "\n\n" nil t)
1104              (point)
1105            (point-max)))
1106         (goto-char (point-min))
1107         ;; Decode MIME headers and charsets.
1108         (when nnmail-mail-splitting-decodes
1109           (let ((mail-parse-charset nnmail-mail-splitting-charset))
1110             (mail-decode-encoded-word-region (point-min) (point-max))))
1111         ;; Fold continuation lines.
1112         (goto-char (point-min))
1113         (while (re-search-forward "\\(\r?\n[ \t]+\\)+" nil t)
1114           (replace-match " " t t))
1115         ;; Nuke pathologically long headers.  Since Gnus applies
1116         ;; pathologically complex regexps to the buffer, lines
1117         ;; that are looong will take longer than the Universe's
1118         ;; existence to process.
1119         (goto-char (point-min))
1120         (while (not (eobp))
1121           (unless (< (move-to-column nnmail-split-header-length-limit)
1122                      nnmail-split-header-length-limit)
1123             (delete-region (point) (point-at-eol)))
1124           (forward-line 1))
1125         ;; Allow washing.
1126         (goto-char (point-min))
1127         (run-hooks 'nnmail-split-hook)
1128         (when (setq nnmail-split-tracing trace)
1129           (setq nnmail-split-trace nil))
1130         (if (and (symbolp nnmail-split-methods)
1131                  (fboundp nnmail-split-methods))
1132             (let ((split
1133                    (condition-case nil
1134                        ;; `nnmail-split-methods' is a function, so we
1135                        ;; just call this function here and use the
1136                        ;; result.
1137                        (or (funcall nnmail-split-methods)
1138                            '("bogus"))
1139                      (error
1140                       (nnheader-message
1141                        5 "Error in `nnmail-split-methods'; using `bogus' mail group")
1142                       (sit-for 1)
1143                       '("bogus")))))
1144               (setq split (mm-delete-duplicates split))
1145               ;; The article may be "cross-posted" to `junk'.  What
1146               ;; to do?  Just remove the `junk' spec.  Don't really
1147               ;; see anything else to do...
1148               (let (elem)
1149                 (while (setq elem (car (memq 'junk split)))
1150                   (setq split (delq elem split))))
1151               (when split
1152                 (setq group-art
1153                       (mapcar
1154                        (lambda (group) (cons group (funcall func group)))
1155                        split))))
1156           ;; Go through the split methods to find a match.
1157           (while (and methods
1158                       (or nnmail-crosspost
1159                           (not group-art)))
1160             (goto-char (point-max))
1161             (setq method (pop methods)
1162                   grp (car method))
1163             (if (or methods
1164                     (not (equal "" (nth 1 method))))
1165                 (when (and
1166                        (ignore-errors
1167                          (if (stringp (nth 1 method))
1168                              (let ((expand (string-match "\\\\[0-9&]" grp))
1169                                    (pos (re-search-backward (cadr method)
1170                                                             nil t)))
1171                                (and expand
1172                                     (setq grp (nnmail-expand-newtext grp)))
1173                                pos)
1174                            ;; Function to say whether this is a match.
1175                            (funcall (nth 1 method) grp)))
1176                        ;; Don't enter the article into the same
1177                        ;; group twice.
1178                        (not (assoc grp group-art)))
1179                   (push (cons grp (funcall func grp))
1180                         group-art))
1181               ;; This is the final group, which is used as a
1182               ;; catch-all.
1183               (unless group-art
1184                 (setq group-art
1185                       (list (cons (car method)
1186                                   (funcall func (car method))))))))
1187           ;; Fall back on "bogus" if all else fails.
1188           (unless group-art
1189             (setq group-art (list (cons "bogus" (funcall func "bogus"))))))
1190         ;; Produce a trace if non-empty.
1191         (when (and trace nnmail-split-trace)
1192           (let ((restore (current-buffer)))
1193             (nnheader-set-temp-buffer "*Split Trace*")
1194             (gnus-add-buffer)
1195             (dolist (trace (nreverse nnmail-split-trace))
1196               (prin1 trace (current-buffer))
1197               (insert "\n"))
1198             (goto-char (point-min))
1199             (gnus-configure-windows 'split-trace)
1200             (set-buffer restore)))
1201         (widen)
1202         ;; See whether the split methods returned `junk'.
1203         (if (equal group-art '(junk))
1204             nil
1205           ;; The article may be "cross-posted" to `junk'.  What
1206           ;; to do?  Just remove the `junk' spec.  Don't really
1207           ;; see anything else to do...
1208           (let (elem)
1209             (while (setq elem (car (memq 'junk group-art)))
1210               (setq group-art (delq elem group-art)))
1211             (nreverse group-art)))))))
1212
1213 (defun nnmail-insert-lines ()
1214   "Insert how many lines there are in the body of the mail.
1215 Return the number of characters in the body."
1216   (let (lines chars)
1217     (save-excursion
1218       (goto-char (point-min))
1219       (unless (search-forward "\n\n" nil t)
1220         (goto-char (point-max))
1221         (insert "\n"))
1222       (setq chars (- (point-max) (point)))
1223       (setq lines (count-lines (point) (point-max)))
1224       (forward-char -1)
1225       (save-excursion
1226         (when (re-search-backward "^Lines: " nil t)
1227           (delete-region (point) (progn (forward-line 1) (point)))))
1228       (beginning-of-line)
1229       (insert (format "Lines: %d\n" (max lines 0)))
1230       chars)))
1231
1232 (defun nnmail-insert-xref (group-alist)
1233   "Insert an Xref line based on the (group . article) alist."
1234   (save-excursion
1235     (goto-char (point-min))
1236     (unless (search-forward "\n\n" nil t)
1237       (goto-char (point-max))
1238       (insert "\n"))
1239     (forward-char -1)
1240     (when (re-search-backward "^Xref: " nil t)
1241       (delete-region (match-beginning 0)
1242                      (progn (forward-line 1) (point))))
1243     (insert (format "Xref: %s" (system-name)))
1244     (while group-alist
1245       (insert (format " %s:%d"
1246                       (mm-encode-coding-string
1247                        (caar group-alist)
1248                        nnmail-pathname-coding-system)
1249                       (cdar group-alist)))
1250       (setq group-alist (cdr group-alist)))
1251     (insert "\n")))
1252
1253 ;;; Message washing functions
1254
1255 (defun nnmail-remove-leading-whitespace ()
1256   "Remove excessive whitespace from all headers."
1257   (goto-char (point-min))
1258   (while (re-search-forward "^\\([^ :]+: \\) +" nil t)
1259     (replace-match "\\1" t)))
1260
1261 (defun nnmail-remove-list-identifiers ()
1262   "Remove list identifiers from Subject headers."
1263   (let ((regexp
1264          (if (consp nnmail-list-identifiers)
1265              (mapconcat 'identity nnmail-list-identifiers " *\\|")
1266            nnmail-list-identifiers)))
1267     (when regexp
1268       (goto-char (point-min))
1269       (while (re-search-forward
1270               (concat "^Subject: +\\(R[Ee]: +\\)*\\(" regexp " *\\)")
1271               nil t)
1272         (delete-region (match-beginning 2) (match-end 0))
1273         (beginning-of-line))
1274       (when (re-search-forward "^Subject: +\\(\\(R[Ee]: +\\)+\\)R[Ee]: +"
1275                                nil t)
1276         (delete-region (match-beginning 1) (match-end 1))
1277         (beginning-of-line)))))
1278
1279 (defun nnmail-remove-tabs ()
1280   "Translate TAB characters into SPACE characters."
1281   (subst-char-in-region (point-min) (point-max) ?\t ?  t))
1282
1283 (defun nnmail-fix-eudora-headers ()
1284   "Eudora has a broken References line, but an OK In-Reply-To."
1285   (goto-char (point-min))
1286   (when (re-search-forward "^X-Mailer:.*Eudora" nil t)
1287     (goto-char (point-min))
1288     (when (re-search-forward "^References:" nil t)
1289       (beginning-of-line)
1290       (insert "X-Gnus-Broken-Eudora-"))
1291     (goto-char (point-min))
1292     (when (re-search-forward "^\\(In-Reply-To:[^\n]+\\)\n[ \t]+" nil t)
1293       (replace-match "\\1" t))))
1294
1295 (custom-add-option 'nnmail-prepare-incoming-header-hook
1296                    'nnmail-fix-eudora-headers)
1297
1298 ;;; Utility functions
1299
1300 (defun nnmail-do-request-post (accept-func &optional server)
1301   "Utility function to directly post a message to an nnmail-derived group.
1302 Calls ACCEPT-FUNC (which should be `nnchoke-request-accept-article')
1303 to actually put the message in the right group."
1304   (let ((success t))
1305     (dolist (mbx (message-unquote-tokens
1306                   (message-tokenize-header
1307                    (message-fetch-field "Newsgroups") ", ")) success)
1308       (let ((to-newsgroup (gnus-group-prefixed-name mbx gnus-command-method)))
1309         (or (gnus-active to-newsgroup)
1310             (gnus-activate-group to-newsgroup)
1311             (if (gnus-y-or-n-p (format "No such group: %s.  Create it? "
1312                                        to-newsgroup))
1313                 (or (and (gnus-request-create-group
1314                           to-newsgroup gnus-command-method)
1315                          (gnus-activate-group to-newsgroup nil nil
1316                                               gnus-command-method))
1317                     (error "Couldn't create group %s" to-newsgroup)))
1318             (error "No such group: %s" to-newsgroup))
1319         (unless (funcall accept-func mbx (nth 1 gnus-command-method))
1320           (setq success nil))))))
1321
1322 (defun nnmail-split-fancy ()
1323   "Fancy splitting method.
1324 See the documentation for the variable `nnmail-split-fancy' for details."
1325   (with-syntax-table nnmail-split-fancy-syntax-table
1326     (nnmail-split-it nnmail-split-fancy)))
1327
1328 (defvar nnmail-split-cache nil)
1329 ;; Alist of split expressions their equivalent regexps.
1330
1331 (defun nnmail-split-it (split)
1332   ;; Return a list of groups matching SPLIT.
1333   (let (cached-pair)
1334     (cond
1335      ;; nil split
1336      ((null split)
1337       nil)
1338
1339      ;; A group name.  Do the \& and \N subs into the string.
1340      ((stringp split)
1341       (when nnmail-split-tracing
1342         (push split nnmail-split-trace))
1343       (list (nnmail-expand-newtext split)))
1344
1345      ;; Junk the message.
1346      ((eq split 'junk)
1347       (when nnmail-split-tracing
1348         (push "junk" nnmail-split-trace))
1349       (list 'junk))
1350
1351      ;; Builtin & operation.
1352      ((eq (car split) '&)
1353       (apply 'nconc (mapcar 'nnmail-split-it (cdr split))))
1354
1355      ;; Builtin | operation.
1356      ((eq (car split) '|)
1357       (let (done)
1358         (while (and (not done) (cdr split))
1359           (setq split (cdr split)
1360                 done (nnmail-split-it (car split))))
1361         done))
1362
1363      ;; Builtin : operation.
1364      ((eq (car split) ':)
1365       (when nnmail-split-tracing
1366         (push split nnmail-split-trace))
1367       (nnmail-split-it (save-excursion (eval (cdr split)))))
1368
1369      ;; Builtin ! operation.
1370      ((eq (car split) '!)
1371       (funcall (cadr split) (nnmail-split-it (caddr split))))
1372
1373      ;; Check the cache for the regexp for this split.
1374      ((setq cached-pair (assq split nnmail-split-cache))
1375       (let (split-result
1376             (end-point (point-max))
1377             (value (nth 1 split)))
1378         (if (symbolp value)
1379             (setq value (cdr (assq value nnmail-split-abbrev-alist))))
1380         (while (and (goto-char end-point)
1381                     (re-search-backward (cdr cached-pair) nil t))
1382           (when nnmail-split-tracing
1383             (push split nnmail-split-trace))
1384           (let ((split-rest (cddr split))
1385                 (end (match-end 0))
1386                 ;; The searched regexp is \(\(FIELD\).*\)\(VALUE\).
1387                 ;; So, start-of-value is the point just before the
1388                 ;; beginning of the value, whereas after-header-name
1389                 ;; is the point just after the field name.
1390                 (start-of-value (match-end 1))
1391                 (after-header-name (match-end 2)))
1392             ;; Start the next search just before the beginning of the
1393             ;; VALUE match.
1394             (setq end-point (1- start-of-value))
1395             ;; Handle - RESTRICTs
1396             (while (eq (car split-rest) '-)
1397               ;; RESTRICT must start after-header-name and
1398               ;; end after start-of-value, so that, for
1399               ;; (any "foo" - "x-foo" "foo.list")
1400               ;; we do not exclude foo.list just because
1401               ;; the header is: ``To: x-foo, foo''
1402               (goto-char end)
1403               (if (and (re-search-backward (cadr split-rest)
1404                                            after-header-name t)
1405                        (> (match-end 0) start-of-value))
1406                   (setq split-rest nil)
1407                 (setq split-rest (cddr split-rest))))
1408             (when split-rest
1409               (goto-char end)
1410               (let ((value (nth 1 split)))
1411                 (if (symbolp value)
1412                     (setq value (cdr (assq value nnmail-split-abbrev-alist))))
1413                 ;; Someone might want to do a \N sub on this match, so get the
1414                 ;; correct match positions.
1415                 (re-search-backward value start-of-value))
1416               (dolist (sp (nnmail-split-it (car split-rest)))
1417                 (unless (member sp split-result)
1418                   (push sp split-result))))))
1419         split-result))
1420
1421      ;; Not in cache, compute a regexp for the field/value pair.
1422      (t
1423       (let* ((field (nth 0 split))
1424              (value (nth 1 split))
1425              partial-front
1426              partial-rear
1427              regexp)
1428         (if (symbolp value)
1429             (setq value (cdr (assq value nnmail-split-abbrev-alist))))
1430         (if (and (>= (length value) 2)
1431                  (string= ".*" (substring value 0 2)))
1432             (setq value (substring value 2)
1433                   partial-front ""))
1434         ;; Same trick for the rear of the regexp
1435         (if (and (>= (length value) 2)
1436                  (string= ".*" (substring value -2)))
1437             (setq value (substring value 0 -2)
1438                   partial-rear ""))
1439         (when nnmail-split-fancy-match-partial-words
1440           (setq partial-front ""
1441                 partial-rear ""))
1442         (setq regexp (concat "^\\(\\("
1443                              (if (symbolp field)
1444                                  (cdr (assq field nnmail-split-abbrev-alist))
1445                                field)
1446                              "\\):.*\\)"
1447                              (or partial-front "\\<")
1448                              "\\("
1449                              value
1450                              "\\)"
1451                              (or partial-rear "\\>")))
1452         (push (cons split regexp) nnmail-split-cache)
1453         ;; Now that it's in the cache, just call nnmail-split-it again
1454     ;; on the same split, which will find it immediately in the cache.
1455         (nnmail-split-it split))))))
1456
1457 (defun nnmail-expand-newtext (newtext)
1458   (let ((len (length newtext))
1459         (pos 0)
1460         c expanded beg N did-expand)
1461     (while (< pos len)
1462       (setq beg pos)
1463       (while (and (< pos len)
1464                   (not (= (aref newtext pos) ?\\)))
1465         (setq pos (1+ pos)))
1466       (unless (= beg pos)
1467         (push (substring newtext beg pos) expanded))
1468       (when (< pos len)
1469         ;; We hit a \; expand it.
1470         (setq did-expand t
1471               pos (1+ pos)
1472               c (aref newtext pos))
1473         (if (not (or (= c ?\&)
1474                      (and (>= c ?1)
1475                           (<= c ?9))))
1476             ;; \ followed by some character we don't expand.
1477             (push (char-to-string c) expanded)
1478           ;; \& or \N
1479           (if (= c ?\&)
1480               (setq N 0)
1481             (setq N (- c ?0)))
1482           (when (match-beginning N)
1483             (push (if nnmail-split-lowercase-expanded
1484                       (downcase (buffer-substring (match-beginning N)
1485                                                   (match-end N)))
1486                     (buffer-substring (match-beginning N) (match-end N)))
1487                   expanded))))
1488       (setq pos (1+ pos)))
1489     (if did-expand
1490         (apply 'concat (nreverse expanded))
1491       newtext)))
1492
1493 ;; Activate a backend only if it isn't already activated.
1494 ;; If FORCE, re-read the active file even if the backend is
1495 ;; already activated.
1496 (defun nnmail-activate (backend &optional force)
1497   (nnheader-init-server-buffer)
1498   (let (file timestamp file-time)
1499     (if (or (not (symbol-value (intern (format "%s-group-alist" backend))))
1500             force
1501             (and (setq file (ignore-errors
1502                               (symbol-value (intern (format "%s-active-file"
1503                                                             backend)))))
1504                  (setq file-time (nth 5 (file-attributes file)))
1505                  (or (not
1506                       (setq timestamp
1507                             (condition-case ()
1508                                 (symbol-value (intern
1509                                                (format "%s-active-timestamp"
1510                                                        backend)))
1511                               (error 'none))))
1512                      (not (consp timestamp))
1513                      (equal timestamp '(0 0))
1514                      (> (nth 0 file-time) (nth 0 timestamp))
1515                      (and (= (nth 0 file-time) (nth 0 timestamp))
1516                           (> (nth 1 file-time) (nth 1 timestamp))))))
1517         (save-excursion
1518           (or (eq timestamp 'none)
1519               (set (intern (format "%s-active-timestamp" backend))
1520                    file-time))
1521           (funcall (intern (format "%s-request-list" backend)))))
1522     t))
1523
1524 (defun nnmail-message-id ()
1525   (concat "<" (message-unique-id) "@totally-fudged-out-message-id>"))
1526
1527 ;;;
1528 ;;; nnmail duplicate handling
1529 ;;;
1530
1531 (defvar nnmail-cache-buffer nil)
1532
1533 (defun nnmail-cache-open ()
1534   (if (or (not nnmail-treat-duplicates)
1535           (and nnmail-cache-buffer
1536                (buffer-name nnmail-cache-buffer)))
1537       ()                                ; The buffer is open.
1538     (save-excursion
1539       (set-buffer
1540        (setq nnmail-cache-buffer
1541              (get-buffer-create " *nnmail message-id cache*")))
1542       (gnus-add-buffer)
1543       (when (file-exists-p nnmail-message-id-cache-file)
1544         (nnheader-insert-file-contents nnmail-message-id-cache-file))
1545       (set-buffer-modified-p nil)
1546       (current-buffer))))
1547
1548 (defun nnmail-cache-close ()
1549   (when (and nnmail-cache-buffer
1550              nnmail-treat-duplicates
1551              (buffer-name nnmail-cache-buffer)
1552              (buffer-modified-p nnmail-cache-buffer))
1553     (save-excursion
1554       (set-buffer nnmail-cache-buffer)
1555       ;; Weed out the excess number of Message-IDs.
1556       (goto-char (point-max))
1557       (when (search-backward "\n" nil t nnmail-message-id-cache-length)
1558         (progn
1559           (beginning-of-line)
1560           (delete-region (point-min) (point))))
1561       ;; Save the buffer.
1562       (or (file-exists-p (file-name-directory nnmail-message-id-cache-file))
1563           (make-directory (file-name-directory nnmail-message-id-cache-file)
1564                           t))
1565       (nnmail-write-region (point-min) (point-max)
1566                            nnmail-message-id-cache-file nil 'silent)
1567       (set-buffer-modified-p nil)
1568       (setq nnmail-cache-buffer nil)
1569       (gnus-kill-buffer (current-buffer)))))
1570
1571 ;; Compiler directives.
1572 (defvar group)
1573 (defvar group-art-list)
1574 (defvar group-art)
1575 (defun nnmail-cache-insert (id grp &optional subject sender)
1576   (when (stringp id)
1577     ;; this will handle cases like `B r' where the group is nil
1578     (let ((grp (or grp gnus-newsgroup-name "UNKNOWN")))
1579       (run-hook-with-args 'nnmail-spool-hook
1580                           id grp subject sender))
1581     (when nnmail-treat-duplicates
1582       ;; Store some information about the group this message is written
1583       ;; to.  This is passed in as the grp argument -- all locations this
1584       ;; has been called from have been checked and the group is available.
1585       ;; The only ambiguous case is nnmail-check-duplication which will only
1586       ;; pass the first (of possibly >1) group which matches. -Josh
1587       (unless (gnus-buffer-live-p nnmail-cache-buffer)
1588         (nnmail-cache-open))
1589       (save-excursion
1590         (set-buffer nnmail-cache-buffer)
1591         (goto-char (point-max))
1592         (if (and grp (not (string= "" grp))
1593                  (gnus-methods-equal-p gnus-command-method
1594                                        (nnmail-cache-primary-mail-backend)))
1595             (let ((regexp (if (consp nnmail-cache-ignore-groups)
1596                               (mapconcat 'identity nnmail-cache-ignore-groups
1597                                          "\\|")
1598                             nnmail-cache-ignore-groups)))
1599               (unless (and regexp (string-match regexp grp))
1600                 (insert id "\t" grp "\n")))
1601           (insert id "\n"))))))
1602
1603 (defun nnmail-cache-primary-mail-backend ()
1604   (let ((be-list (cons gnus-select-method gnus-secondary-select-methods))
1605         (be nil)
1606         (res nil)
1607         (get-new-mail nil))
1608     (while (and (null res) be-list)
1609       (setq be (car be-list))
1610       (setq be-list (cdr be-list))
1611       (when (and (gnus-method-option-p be 'respool)
1612                  (setq get-new-mail
1613                        (intern (format "%s-get-new-mail" (car be))))
1614                  (boundp get-new-mail)
1615                  (symbol-value get-new-mail))
1616         (setq res be)))
1617     res))
1618
1619 ;; Fetch the group name corresponding to the message id stored in the
1620 ;; cache.
1621 (defun nnmail-cache-fetch-group (id)
1622   (when (and nnmail-treat-duplicates nnmail-cache-buffer)
1623     (save-excursion
1624       (set-buffer nnmail-cache-buffer)
1625       (goto-char (point-max))
1626       (when (search-backward id nil t)
1627         (beginning-of-line)
1628         (skip-chars-forward "^\n\r\t")
1629         (unless (looking-at "[\r\n]")
1630           (forward-char 1)
1631           (buffer-substring (point) (point-at-eol)))))))
1632
1633 ;; Function for nnmail-split-fancy: look up all references in the
1634 ;; cache and if a match is found, return that group.
1635 (defun nnmail-split-fancy-with-parent ()
1636   "Split this message into the same group as its parent.
1637 This function can be used as an entry in `nnmail-split-fancy', for
1638 example like this: (: nnmail-split-fancy-with-parent)
1639 For a message to be split, it looks for the parent message in the
1640 References or In-Reply-To header and then looks in the message id
1641 cache file (given by the variable `nnmail-message-id-cache-file') to
1642 see which group that message was put in.  This group is returned.
1643
1644 See the Info node `(gnus)Fancy Mail Splitting' for more details."
1645   (let* ((refstr (or (message-fetch-field "references")
1646                      (message-fetch-field "in-reply-to")))
1647          (references nil)
1648          (res nil)
1649          (regexp (if (consp nnmail-split-fancy-with-parent-ignore-groups)
1650                      (mapconcat
1651                       (lambda (x) (format "\\(%s\\)" x))
1652                       nnmail-split-fancy-with-parent-ignore-groups
1653                       "\\|")
1654                    nnmail-split-fancy-with-parent-ignore-groups)))
1655     (when refstr
1656       (setq references (nreverse (gnus-split-references refstr)))
1657       (unless (gnus-buffer-live-p nnmail-cache-buffer)
1658         (nnmail-cache-open))
1659       (mapcar (lambda (x)
1660                 (setq res (or (nnmail-cache-fetch-group x) res))
1661                 (when (or (member res '("delayed" "drafts" "queue"))
1662                           (and regexp res (string-match regexp res)))
1663                   (setq res nil)))
1664               references)
1665       res)))
1666
1667 (defun nnmail-cache-id-exists-p (id)
1668   (when nnmail-treat-duplicates
1669     (save-excursion
1670       (set-buffer nnmail-cache-buffer)
1671       (goto-char (point-max))
1672       (search-backward id nil t))))
1673
1674 (defun nnmail-fetch-field (header)
1675   (save-excursion
1676     (save-restriction
1677       (message-narrow-to-head)
1678       (message-fetch-field header))))
1679
1680 (defun nnmail-check-duplication (message-id func artnum-func)
1681   (run-hooks 'nnmail-prepare-incoming-message-hook)
1682   ;; If this is a duplicate message, then we do not save it.
1683   (let* ((duplication (nnmail-cache-id-exists-p message-id))
1684          (case-fold-search t)
1685          (action (when duplication
1686                    (cond
1687                     ((memq nnmail-treat-duplicates '(warn delete))
1688                      nnmail-treat-duplicates)
1689                     ((functionp nnmail-treat-duplicates)
1690                      (funcall nnmail-treat-duplicates message-id))
1691                     (t
1692                      nnmail-treat-duplicates))))
1693          group-art)
1694     ;; We insert a line that says what the mail source is.
1695     (let ((case-fold-search t))
1696       (goto-char (point-min))
1697       (re-search-forward "^message-id[ \t]*:" nil t)
1698       (beginning-of-line)
1699       (insert (format "X-Gnus-Mail-Source: %s\n" mail-source-string)))
1700
1701     ;; Let the backend save the article (or not).
1702     (cond
1703      ((not duplication)
1704       (funcall func (setq group-art
1705                           (nreverse (nnmail-article-group artnum-func))))
1706       (nnmail-cache-insert message-id (caar group-art)))
1707      ((eq action 'delete)
1708       (setq group-art nil))
1709      ((eq action 'warn)
1710       ;; We insert a warning.
1711       (let ((case-fold-search t))
1712         (goto-char (point-min))
1713         (re-search-forward "^message-id[ \t]*:" nil t)
1714         (beginning-of-line)
1715         (insert
1716          "Gnus-Warning: This is a duplicate of message " message-id "\n")
1717         (funcall func (setq group-art
1718                             (nreverse (nnmail-article-group artnum-func))))))
1719      (t
1720       (funcall func (setq group-art
1721                           (nreverse (nnmail-article-group artnum-func))))))
1722     ;; Add the group-art list to the history list.
1723     (if group-art
1724         (push group-art nnmail-split-history)
1725       (delete-region (point-min) (point-max)))))
1726
1727 ;;; Get new mail.
1728
1729 (defvar nnmail-fetched-sources nil)
1730
1731 (defun nnmail-get-value (&rest args)
1732   (let ((sym (intern (apply 'format args))))
1733     (when (boundp sym)
1734       (symbol-value sym))))
1735
1736 (defun nnmail-get-new-mail (method exit-func temp
1737                                    &optional group spool-func)
1738   "Read new incoming mail."
1739   (let* ((sources (or mail-sources
1740                       (if (listp nnmail-spool-file) nnmail-spool-file
1741                         (list nnmail-spool-file))))
1742          fetching-sources
1743          (group-in group)
1744          (i 0)
1745          (new 0)
1746          (total 0)
1747          incoming incomings source)
1748     (when (and (nnmail-get-value "%s-get-new-mail" method)
1749                sources)
1750       (while (setq source (pop sources))
1751         ;; Be compatible with old values.
1752         (cond
1753          ((stringp source)
1754           (setq source
1755                 (cond
1756                  ((string-match "^po:" source)
1757                   (list 'pop :user (substring source (match-end 0))))
1758                  ((file-directory-p source)
1759                   (list 'directory :path source))
1760                  (t
1761                   (list 'file :path source)))))
1762          ((eq source 'procmail)
1763           (message "Invalid value for nnmail-spool-file: `procmail'")
1764           nil))
1765         ;; Hack to only fetch the contents of a single group's spool file.
1766         (when (and (eq (car source) 'directory)
1767                    (null nnmail-scan-directory-mail-source-once)
1768                    group)
1769           (mail-source-bind (directory source)
1770             (setq source (append source
1771                                  (list
1772                                   :predicate
1773                                   (gnus-byte-compile
1774                                    `(lambda (file)
1775                                       (string-equal
1776                                        ,(concat group suffix)
1777                                        (file-name-nondirectory file)))))))))
1778         (when nnmail-fetched-sources
1779           (if (member source nnmail-fetched-sources)
1780               (setq source nil)
1781             (push source nnmail-fetched-sources)
1782             (push source fetching-sources)))))
1783     (when fetching-sources
1784       ;; We first activate all the groups.
1785       (nnmail-activate method)
1786       ;; Allow the user to hook.
1787       (run-hooks 'nnmail-pre-get-new-mail-hook)
1788       ;; Open the message-id cache.
1789       (nnmail-cache-open)
1790       ;; The we go through all the existing mail source specification
1791       ;; and fetch the mail from each.
1792       (while (setq source (pop fetching-sources))
1793         (nnheader-message 4 "%s: Reading incoming mail from %s..."
1794                           method (car source))
1795         (when (setq new
1796                     (mail-source-fetch
1797                      source
1798                      (gnus-byte-compile
1799                       `(lambda (file orig-file)
1800                          (nnmail-split-incoming
1801                           file ',(intern (format "%s-save-mail" method))
1802                           ',spool-func
1803                           (if (equal file orig-file)
1804                               nil
1805                             (nnmail-get-split-group orig-file ',source))
1806                           ',(intern (format "%s-active-number" method)))))))
1807           (incf total new)
1808           (incf i)))
1809       ;; If we did indeed read any incoming spools, we save all info.
1810       (if (zerop total)
1811           (nnheader-message 4 "%s: Reading incoming mail (no new mail)...done"
1812                             method (car source))
1813         (nnmail-save-active
1814          (nnmail-get-value "%s-group-alist" method)
1815          (nnmail-get-value "%s-active-file" method))
1816         (when exit-func
1817           (funcall exit-func))
1818         (run-hooks 'nnmail-read-incoming-hook)
1819         (nnheader-message 4 "%s: Reading incoming mail (%d new)...done" method
1820                           total))
1821       ;; Close the message-id cache.
1822       (nnmail-cache-close)
1823       ;; Allow the user to hook.
1824       (run-hooks 'nnmail-post-get-new-mail-hook))))
1825
1826 (defun nnmail-expired-article-p (group time force &optional inhibit)
1827   "Say whether an article that is TIME old in GROUP should be expired."
1828   (if force
1829       t
1830     (let ((days (or (and nnmail-expiry-wait-function
1831                          (funcall nnmail-expiry-wait-function group))
1832                     nnmail-expiry-wait)))
1833       (cond ((or (eq days 'never)
1834                  (and (not force)
1835                       inhibit))
1836              ;; This isn't an expirable group.
1837              nil)
1838             ((eq days 'immediate)
1839              ;; We expire all articles on sight.
1840              t)
1841             ((equal time '(0 0))
1842             ;; This is an ange-ftp group, and we don't have any dates.
1843              nil)
1844             ((numberp days)
1845              (setq days (days-to-time days))
1846              ;; Compare the time with the current time.
1847              (ignore-errors (time-less-p days (time-since time))))))))
1848
1849 (defun nnmail-expiry-target-group (target group)
1850   ;; Do not invoke this from nntp-server-buffer!  At least nnfolder clears
1851   ;; that buffer if the nnfolder group isn't selected.
1852   (let (nnmail-cache-accepted-message-ids)
1853     ;; Don't enter Message-IDs into cache.
1854     ;; Let users hack it in TARGET function.
1855     (when (functionp target)
1856       (setq target (funcall target group)))
1857     (unless (eq target 'delete)
1858       (when (or (gnus-request-group target)
1859                 (gnus-request-create-group target))
1860         (let ((group-art (gnus-request-accept-article target nil nil t)))
1861           (when (consp group-art)
1862             (gnus-group-mark-article-read target (cdr group-art))))))))
1863
1864 (defun nnmail-fancy-expiry-target (group)
1865   "Returns a target expiry group determined by `nnmail-fancy-expiry-targets'."
1866   (let* (header
1867          (case-fold-search nil)
1868          (from (or (message-fetch-field "from") ""))
1869          (to (or (message-fetch-field "to") ""))
1870          (date (message-fetch-field "date"))
1871          (target 'delete))
1872     (setq date (if date
1873                    (condition-case err
1874                        (date-to-time date)
1875                      (error
1876                       (message "%s" (error-message-string err))
1877                       (current-time)))
1878                  (current-time)))
1879     (dolist (regexp-target-pair (reverse nnmail-fancy-expiry-targets) target)
1880       (setq header (car regexp-target-pair))
1881       (cond
1882        ;; If the header is to-from then match against the
1883        ;; To or From header
1884        ((and (equal header 'to-from)
1885              (or (string-match (cadr regexp-target-pair) from)
1886                  (and (string-match message-dont-reply-to-names from)
1887                       (string-match (cadr regexp-target-pair) to))))
1888         (setq target (format-time-string (caddr regexp-target-pair) date)))
1889        ((and (not (equal header 'to-from))
1890              (string-match (cadr regexp-target-pair)
1891                            (or
1892                             (message-fetch-field header)
1893                             "")))
1894         (setq target
1895               (format-time-string (caddr regexp-target-pair) date)))))))
1896
1897 (defun nnmail-check-syntax ()
1898   "Check (and modify) the syntax of the message in the current buffer."
1899   (save-restriction
1900     (message-narrow-to-head)
1901     (let ((case-fold-search t))
1902       (unless (re-search-forward "^Message-ID[ \t]*:" nil t)
1903         (insert "Message-ID: " (nnmail-message-id) "\n")))))
1904
1905 (defun nnmail-write-region (start end filename &optional append visit lockname)
1906   "Do a `write-region', and then set the file modes."
1907   (let ((coding-system-for-write nnmail-file-coding-system)
1908         (file-name-coding-system nnmail-pathname-coding-system))
1909     (write-region start end filename append visit lockname)
1910     (set-file-modes filename nnmail-default-file-modes)))
1911
1912 ;;;
1913 ;;; Status functions
1914 ;;;
1915
1916 (defun nnmail-replace-status (name value)
1917   "Make status NAME and VALUE part of the current status line."
1918   (save-restriction
1919     (message-narrow-to-head)
1920     (let ((status (nnmail-decode-status)))
1921       (setq status (delq (member name status) status))
1922       (when value
1923         (push (cons name value) status))
1924       (message-remove-header "status")
1925       (goto-char (point-max))
1926       (insert "Status: " (nnmail-encode-status status) "\n"))))
1927
1928 (defun nnmail-decode-status ()
1929   "Return a status-value alist from STATUS."
1930   (goto-char (point-min))
1931   (when (re-search-forward "^Status: " nil t)
1932     (let (name value status)
1933       (save-restriction
1934         ;; Narrow to the status.
1935         (narrow-to-region
1936          (point)
1937          (if (re-search-forward "^[^ \t]" nil t)
1938              (1- (point))
1939            (point-max)))
1940         ;; Go through all elements and add them to the list.
1941         (goto-char (point-min))
1942         (while (re-search-forward "[^ \t=]+" nil t)
1943           (setq name (match-string 0))
1944           (if (not (eq (char-after) ?=))
1945               ;; Implied "yes".
1946               (setq value "yes")
1947             (forward-char 1)
1948             (if (not (eq (char-after) ?\"))
1949                 (if (not (looking-at "[^ \t]"))
1950                     ;; Implied "no".
1951                     (setq value "no")
1952                   ;; Unquoted value.
1953                   (setq value (match-string 0))
1954                   (goto-char (match-end 0)))
1955               ;; Quoted value.
1956               (setq value (read (current-buffer)))))
1957           (push (cons name value) status)))
1958       status)))
1959
1960 (defun nnmail-encode-status (status)
1961   "Return a status string from STATUS."
1962   (mapconcat
1963    (lambda (elem)
1964      (concat
1965       (car elem) "="
1966       (if (string-match "[ \t]" (cdr elem))
1967           (prin1-to-string (cdr elem))
1968         (cdr elem))))
1969    status " "))
1970
1971 (defun nnmail-split-history ()
1972   "Generate an overview of where the last mail split put articles."
1973   (interactive)
1974   (unless nnmail-split-history
1975     (error "No current split history"))
1976   (with-output-to-temp-buffer "*nnmail split history*"
1977     (with-current-buffer standard-output
1978       (fundamental-mode))               ; for Emacs 20.4+
1979       (dolist (elem nnmail-split-history)
1980         (princ (mapconcat (lambda (ga)
1981                             (concat (car ga) ":" (int-to-string (cdr ga))))
1982                           elem
1983                           ", "))
1984         (princ "\n"))))
1985
1986 (defun nnmail-purge-split-history (group)
1987   "Remove all instances of GROUP from `nnmail-split-history'."
1988   (let ((history nnmail-split-history))
1989     (while history
1990       (setcar history (gnus-remove-if (lambda (e) (string= (car e) group))
1991                                       (car history)))
1992       (pop history))
1993     (setq nnmail-split-history (delq nil nnmail-split-history))))
1994
1995 (defun nnmail-new-mail-p (group)
1996   "Say whether GROUP has new mail."
1997   (let ((his nnmail-split-history)
1998         found)
1999     (while his
2000       (when (assoc group (pop his))
2001         (setq found t
2002               his nil)))
2003     found))
2004
2005 (defun nnmail-within-headers-p ()
2006   "Check to see if point is within the headers of a unix mail message.
2007 Doesn't change point."
2008   (let ((pos (point)))
2009     (save-excursion
2010       (and (nnmail-search-unix-mail-delim-backward)
2011            (not (search-forward "\n\n" pos t))))))
2012
2013 (run-hooks 'nnmail-load-hook)
2014
2015 (provide 'nnmail)
2016
2017 ;;; arch-tag: fe8f671a-50db-428a-bb5d-f00462f72ed7
2018 ;;; nnmail.el ends here