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