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