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