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