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