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