(message-user-agent): Don't wrap ignore-errors around
[gnus] / lisp / message.el
1 ;;; message.el --- composing mail and news messages
2 ;; Copyright (C) 1996, 1997, 1998, 1999, 2000
3 ;;        Free Software Foundation, Inc.
4
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;; Keywords: mail, news
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
13 ;; any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
22 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
24
25 ;;; Commentary:
26
27 ;; This mode provides mail-sending facilities from within Emacs.  It
28 ;; consists mainly of large chunks of code from the sendmail.el,
29 ;; gnus-msg.el and rnewspost.el files.
30
31 ;;; Code:
32
33 (eval-when-compile
34   (require 'cl)
35   (defvar gnus-list-identifiers))       ; gnus-sum is required where necessary
36 (require 'mailheader)
37 (require 'nnheader)
38 ;; This is apparently necessary even though things are autoloaded:
39 (if (featurep 'xemacs)
40     (require 'mail-abbrevs))
41 (require 'mail-parse)
42 (require 'mml)
43
44 (defgroup message '((user-mail-address custom-variable)
45                     (user-full-name custom-variable))
46   "Mail and news message composing."
47   :link '(custom-manual "(message)Top")
48   :group 'mail
49   :group 'news)
50
51 (put 'user-mail-address 'custom-type 'string)
52 (put 'user-full-name 'custom-type 'string)
53
54 (defgroup message-various nil
55   "Various Message Variables"
56   :link '(custom-manual "(message)Various Message Variables")
57   :group 'message)
58
59 (defgroup message-buffers nil
60   "Message Buffers"
61   :link '(custom-manual "(message)Message Buffers")
62   :group 'message)
63
64 (defgroup message-sending nil
65   "Message Sending"
66   :link '(custom-manual "(message)Sending Variables")
67   :group 'message)
68
69 (defgroup message-interface nil
70   "Message Interface"
71   :link '(custom-manual "(message)Interface")
72   :group 'message)
73
74 (defgroup message-forwarding nil
75   "Message Forwarding"
76   :link '(custom-manual "(message)Forwarding")
77   :group 'message-interface)
78
79 (defgroup message-insertion nil
80   "Message Insertion"
81   :link '(custom-manual "(message)Insertion")
82   :group 'message)
83
84 (defgroup message-headers nil
85   "Message Headers"
86   :link '(custom-manual "(message)Message Headers")
87   :group 'message)
88
89 (defgroup message-news nil
90   "Composing News Messages"
91   :group 'message)
92
93 (defgroup message-mail nil
94   "Composing Mail Messages"
95   :group 'message)
96
97 (defgroup message-faces nil
98   "Faces used for message composing."
99   :group 'message
100   :group 'faces)
101
102 (defcustom message-directory "~/Mail/"
103   "*Directory from which all other mail file variables are derived."
104   :group 'message-various
105   :type 'directory)
106
107 (defcustom message-max-buffers 10
108   "*How many buffers to keep before starting to kill them off."
109   :group 'message-buffers
110   :type 'integer)
111
112 (defcustom message-send-rename-function nil
113   "Function called to rename the buffer after sending it."
114   :group 'message-buffers
115   :type 'function)
116
117 (defcustom message-fcc-handler-function 'message-output
118   "*A function called to save outgoing articles.
119 This function will be called with the name of the file to store the
120 article in.  The default function is `message-output' which saves in Unix
121 mailbox format."
122   :type '(radio (function-item message-output)
123                 (function :tag "Other"))
124   :group 'message-sending)
125
126 (defcustom message-courtesy-message
127   "The following message is a courtesy copy of an article\nthat has been posted to %s as well.\n\n"
128   "*This is inserted at the start of a mailed copy of a posted message.
129 If the string contains the format spec \"%s\", the Newsgroups
130 the article has been posted to will be inserted there.
131 If this variable is nil, no such courtesy message will be added."
132   :group 'message-sending
133   :type 'string)
134
135 (defcustom message-ignored-bounced-headers "^\\(Received\\|Return-Path\\):"
136   "*Regexp that matches headers to be removed in resent bounced mail."
137   :group 'message-interface
138   :type 'regexp)
139
140 ;;;###autoload
141 (defcustom message-from-style 'default
142   "*Specifies how \"From\" headers look.
143
144 If `nil', they contain just the return address like:
145         king@grassland.com
146 If `parens', they look like:
147         king@grassland.com (Elvis Parsley)
148 If `angles', they look like:
149         Elvis Parsley <king@grassland.com>
150
151 Otherwise, most addresses look like `angles', but they look like
152 `parens' if `angles' would need quoting and `parens' would not."
153   :type '(choice (const :tag "simple" nil)
154                  (const parens)
155                  (const angles)
156                  (const default))
157   :group 'message-headers)
158
159 (defcustom message-syntax-checks nil
160   ;; Guess this one shouldn't be easy to customize...
161   "*Controls what syntax checks should not be performed on outgoing posts.
162 To disable checking of long signatures, for instance, add
163  `(signature . disabled)' to this list.
164
165 Don't touch this variable unless you really know what you're doing.
166
167 Checks include subject-cmsg multiple-headers sendsys message-id from
168 long-lines control-chars size new-text quoting-style
169 redirected-followup signature approved sender empty empty-headers
170 message-id from subject shorten-followup-to existing-newsgroups
171 buffer-file-name unchanged newsgroups."
172   :group 'message-news
173   :type '(repeat sexp))
174
175 (defcustom message-required-news-headers
176   '(From Newsgroups Subject Date Message-ID
177          (optional . Organization) Lines
178          (optional . User-Agent))
179   "*Headers to be generated or prompted for when posting an article.
180 RFC977 and RFC1036 require From, Date, Newsgroups, Subject,
181 Message-ID.  Organization, Lines, In-Reply-To, Expires, and
182 User-Agent are optional.  If don't you want message to insert some
183 header, remove it from this list."
184   :group 'message-news
185   :group 'message-headers
186   :type '(repeat sexp))
187
188 (defcustom message-required-mail-headers
189   '(From Subject Date (optional . In-Reply-To) Message-ID Lines
190          (optional . User-Agent))
191   "*Headers to be generated or prompted for when mailing a message.
192 RFC822 required that From, Date, To, Subject and Message-ID be
193 included.  Organization, Lines and User-Agent are optional."
194   :group 'message-mail
195   :group 'message-headers
196   :type '(repeat sexp))
197
198 (defcustom message-deletable-headers '(Message-ID Date Lines)
199   "Headers to be deleted if they already exist and were generated by message previously."
200   :group 'message-headers
201   :type 'sexp)
202
203 (defcustom message-ignored-news-headers
204   "^NNTP-Posting-Host:\\|^Xref:\\|^[BGF]cc:\\|^Resent-Fcc:"
205   "*Regexp of headers to be removed unconditionally before posting."
206   :group 'message-news
207   :group 'message-headers
208   :type 'regexp)
209
210 (defcustom message-ignored-mail-headers "^[GF]cc:\\|^Resent-Fcc:\\|^Xref:"
211   "*Regexp of headers to be removed unconditionally before mailing."
212   :group 'message-mail
213   :group 'message-headers
214   :type 'regexp)
215
216 (defcustom message-ignored-supersedes-headers "^Path:\\|^Date\\|^NNTP-Posting-Host:\\|^Xref:\\|^Lines:\\|^Received:\\|^X-From-Line:\\|^X-Trace:\\|^X-Complaints-To:\\|Return-Path:\\|^Supersedes:\\|^NNTP-Posting-Date:\\|^X-Trace:\\|^X-Complaints-To:"
217   "*Header lines matching this regexp will be deleted before posting.
218 It's best to delete old Path and Date headers before posting to avoid
219 any confusion."
220   :group 'message-interface
221   :type 'regexp)
222
223 (defcustom message-subject-re-regexp "^[ \t]*\\([Rr][Ee]:[ \t]*\\)*[ \t]*"
224   "*Regexp matching \"Re: \" in the subject line."
225   :group 'message-various
226   :type 'regexp)
227
228 ;;;###autoload
229 (defcustom message-signature-separator "^-- *$"
230   "Regexp matching the signature separator."
231   :type 'regexp
232   :group 'message-various)
233
234 (defcustom message-elide-ellipsis "\n[...]\n\n"
235   "*The string which is inserted for elided text."
236   :type 'string
237   :group 'message-various)
238
239 (defcustom message-interactive nil
240   "Non-nil means when sending a message wait for and display errors.
241 nil means let mailer mail back a message to report errors."
242   :group 'message-sending
243   :group 'message-mail
244   :type 'boolean)
245
246 (defcustom message-generate-new-buffers 'unique
247   "*Non-nil means that a new message buffer will be created whenever `message-setup' is called.
248 If this is a function, call that function with three parameters:  The type,
249 the to address and the group name.  (Any of these may be nil.)  The function
250 should return the new buffer name."
251   :group 'message-buffers
252   :type '(choice (const :tag "off" nil)
253                  (const :tag "unique" unique)
254                  (const :tag "unsent" unsent)
255                  (function fun)))
256
257 (defcustom message-kill-buffer-on-exit nil
258   "*Non-nil means that the message buffer will be killed after sending a message."
259   :group 'message-buffers
260   :type 'boolean)
261
262 (defvar gnus-local-organization)
263 (defcustom message-user-organization
264   (or (and (boundp 'gnus-local-organization)
265            (stringp gnus-local-organization)
266            gnus-local-organization)
267       (getenv "ORGANIZATION")
268       t)
269   "*String to be used as an Organization header.
270 If t, use `message-user-organization-file'."
271   :group 'message-headers
272   :type '(choice string
273                  (const :tag "consult file" t)))
274
275 ;;;###autoload
276 (defcustom message-user-organization-file "/usr/lib/news/organization"
277   "*Local news organization file."
278   :type 'file
279   :group 'message-headers)
280
281 (defcustom message-make-forward-subject-function
282   'message-forward-subject-author-subject
283   "*A list of functions that are called to generate a subject header for forwarded messages.
284 The subject generated by the previous function is passed into each
285 successive function.
286
287 The provided functions are:
288
289 * message-forward-subject-author-subject (Source of article (author or
290       newsgroup)), in brackets followed by the subject
291 * message-forward-subject-fwd (Subject of article with 'Fwd:' prepended
292       to it."
293   :group 'message-forwarding
294   :type '(radio (function-item message-forward-subject-author-subject)
295                 (function-item message-forward-subject-fwd)))
296
297 (defcustom message-forward-as-mime t
298   "*If non-nil, forward messages as an inline/rfc822 MIME section.  Otherwise, directly inline the old message in the forwarded message."
299   :group 'message-forwarding
300   :type 'boolean)
301
302 (defcustom message-forward-show-mml t
303   "*If non-nil, forward messages are shown as mml.  Otherwise, forward messages are unchanged."
304   :group 'message-forwarding
305   :type 'boolean)
306
307 (defcustom message-forward-before-signature t
308   "*If non-nil, put forwarded message before signature, else after."
309   :group 'message-forwarding
310   :type 'boolean)
311
312 (defcustom message-wash-forwarded-subjects nil
313   "*If non-nil, try to remove as much old cruft as possible from the subject of messages before generating the new subject of a forward."
314   :group 'message-forwarding
315   :type 'boolean)
316
317 (defcustom message-ignored-resent-headers "^Return-receipt\\|^X-Gnus\\|^Gnus-Warning:"
318   "*All headers that match this regexp will be deleted when resending a message."
319   :group 'message-interface
320   :type 'regexp)
321
322 (defcustom message-forward-ignored-headers "^Content-Transfer-Encoding:\\|^X-Gnus"
323   "*All headers that match this regexp will be deleted when forwarding a message."
324   :group 'message-forwarding
325   :type '(choice (const :tag "None" nil)
326                  regexp))
327
328 (defcustom message-ignored-cited-headers "."
329   "*Delete these headers from the messages you yank."
330   :group 'message-insertion
331   :type 'regexp)
332
333 (defcustom message-cancel-message "I am canceling my own article.\n"
334   "Message to be inserted in the cancel message."
335   :group 'message-interface
336   :type 'string)
337
338 ;; Useful to set in site-init.el
339 ;;;###autoload
340 (defcustom message-send-mail-function 'message-send-mail-with-sendmail
341   "Function to call to send the current buffer as mail.
342 The headers should be delimited by a line whose contents match the
343 variable `mail-header-separator'.
344
345 Valid values include `message-send-mail-with-sendmail' (the default),
346 `message-send-mail-with-mh', `message-send-mail-with-qmail' and
347 `smtpmail-send-it'."
348   :type '(radio (function-item message-send-mail-with-sendmail)
349                 (function-item message-send-mail-with-mh)
350                 (function-item message-send-mail-with-qmail)
351                 (function-item smtpmail-send-it)
352                 (function :tag "Other"))
353   :group 'message-sending
354   :group 'message-mail)
355
356 (defcustom message-send-news-function 'message-send-news
357   "Function to call to send the current buffer as news.
358 The headers should be delimited by a line whose contents match the
359 variable `mail-header-separator'."
360   :group 'message-sending
361   :group 'message-news
362   :type 'function)
363
364 (defcustom message-reply-to-function nil
365   "Function that should return a list of headers.
366 This function should pick out addresses from the To, Cc, and From headers
367 and respond with new To and Cc headers."
368   :group 'message-interface
369   :type 'function)
370
371 (defcustom message-wide-reply-to-function nil
372   "Function that should return a list of headers.
373 This function should pick out addresses from the To, Cc, and From headers
374 and respond with new To and Cc headers."
375   :group 'message-interface
376   :type 'function)
377
378 (defcustom message-followup-to-function nil
379   "Function that should return a list of headers.
380 This function should pick out addresses from the To, Cc, and From headers
381 and respond with new To and Cc headers."
382   :group 'message-interface
383   :type 'function)
384
385 (defcustom message-use-followup-to 'ask
386   "*Specifies what to do with Followup-To header.
387 If nil, always ignore the header.  If it is t, use its value, but
388 query before using the \"poster\" value.  If it is the symbol `ask',
389 always query the user whether to use the value.  If it is the symbol
390 `use', always use the value."
391   :group 'message-interface
392   :type '(choice (const :tag "ignore" nil)
393                  (const use)
394                  (const ask)))
395
396 (defcustom message-sendmail-f-is-evil nil
397   "*Non-nil means that \"-f username\" should not be added to the sendmail command line.
398 Doing so would be even more evil than leaving it out."
399   :group 'message-sending
400   :type 'boolean)
401
402 ;; qmail-related stuff
403 (defcustom message-qmail-inject-program "/var/qmail/bin/qmail-inject"
404   "Location of the qmail-inject program."
405   :group 'message-sending
406   :type 'file)
407
408 (defcustom message-qmail-inject-args nil
409   "Arguments passed to qmail-inject programs.
410 This should be a list of strings, one string for each argument.
411
412 For e.g., if you wish to set the envelope sender address so that bounces
413 go to the right place or to deal with listserv's usage of that address, you
414 might set this variable to '(\"-f\" \"you@some.where\")."
415   :group 'message-sending
416   :type '(repeat string))
417
418 (defvar message-cater-to-broken-inn t
419   "Non-nil means Gnus should not fold the `References' header.
420 Folding `References' makes ancient versions of INN create incorrect
421 NOV lines.")
422
423 (defvar gnus-post-method)
424 (defvar gnus-select-method)
425 (defcustom message-post-method
426   (cond ((and (boundp 'gnus-post-method)
427               (listp gnus-post-method)
428               gnus-post-method)
429          gnus-post-method)
430         ((boundp 'gnus-select-method)
431          gnus-select-method)
432         (t '(nnspool "")))
433   "*Method used to post news.
434 Note that when posting from inside Gnus, for instance, this
435 variable isn't used."
436   :group 'message-news
437   :group 'message-sending
438   ;; This should be the `gnus-select-method' widget, but that might
439   ;; create a dependence to `gnus.el'.
440   :type 'sexp)
441
442 (defcustom message-generate-headers-first nil
443   "*If non-nil, generate all possible headers before composing."
444   :group 'message-headers
445   :type 'boolean)
446
447 (defcustom message-setup-hook nil
448   "Normal hook, run each time a new outgoing message is initialized.
449 The function `message-setup' runs this hook."
450   :group 'message-various
451   :type 'hook)
452
453 (defcustom message-cancel-hook nil
454   "Hook run when cancelling articles."
455   :group 'message-various
456   :type 'hook)
457
458 (defcustom message-signature-setup-hook nil
459   "Normal hook, run each time a new outgoing message is initialized.
460 It is run after the headers have been inserted and before
461 the signature is inserted."
462   :group 'message-various
463   :type 'hook)
464
465 (defcustom message-mode-hook nil
466   "Hook run in message mode buffers."
467   :group 'message-various
468   :type 'hook)
469
470 (defcustom message-header-hook nil
471   "Hook run in a message mode buffer narrowed to the headers."
472   :group 'message-various
473   :type 'hook)
474
475 (defcustom message-header-setup-hook nil
476   "Hook called narrowed to the headers when setting up a message buffer."
477   :group 'message-various
478   :type 'hook)
479
480 ;;;###autoload
481 (defcustom message-citation-line-function 'message-insert-citation-line
482   "*Function called to insert the \"Whomever writes:\" line."
483   :type 'function
484   :group 'message-insertion)
485
486 ;;;###autoload
487 (defcustom message-yank-prefix "> "
488   "*Prefix inserted on the lines of yanked messages."
489   :type 'string
490   :group 'message-insertion)
491
492 (defcustom message-indentation-spaces 3
493   "*Number of spaces to insert at the beginning of each cited line.
494 Used by `message-yank-original' via `message-yank-cite'."
495   :group 'message-insertion
496   :type 'integer)
497
498 ;;;###autoload
499 (defcustom message-cite-function 'message-cite-original
500   "*Function for citing an original message.
501 Predefined functions include `message-cite-original' and
502 `message-cite-original-without-signature'.
503 Note that `message-cite-original' uses `mail-citation-hook' if that is non-nil."
504   :type '(radio (function-item message-cite-original)
505                 (function-item message-cite-original-without-signature)
506                 (function-item sc-cite-original)
507                 (function :tag "Other"))
508   :group 'message-insertion)
509
510 ;;;###autoload
511 (defcustom message-indent-citation-function 'message-indent-citation
512   "*Function for modifying a citation just inserted in the mail buffer.
513 This can also be a list of functions.  Each function can find the
514 citation between (point) and (mark t).  And each function should leave
515 point and mark around the citation text as modified."
516   :type 'function
517   :group 'message-insertion)
518
519 (defvar message-abbrevs-loaded nil)
520
521 ;;;###autoload
522 (defcustom message-signature t
523   "*String to be inserted at the end of the message buffer.
524 If t, the `message-signature-file' file will be inserted instead.
525 If a function, the result from the function will be used instead.
526 If a form, the result from the form will be used instead."
527   :type 'sexp
528   :group 'message-insertion)
529
530 ;;;###autoload
531 (defcustom message-signature-file "~/.signature"
532   "*File containing the text inserted at end of message buffer."
533   :type 'file
534   :group 'message-insertion)
535
536 (defcustom message-distribution-function nil
537   "*Function called to return a Distribution header."
538   :group 'message-news
539   :group 'message-headers
540   :type 'function)
541
542 (defcustom message-expires 14
543   "Number of days before your article expires."
544   :group 'message-news
545   :group 'message-headers
546   :link '(custom-manual "(message)News Headers")
547   :type 'integer)
548
549 (defcustom message-user-path nil
550   "If nil, use the NNTP server name in the Path header.
551 If stringp, use this; if non-nil, use no host name (user name only)."
552   :group 'message-news
553   :group 'message-headers
554   :link '(custom-manual "(message)News Headers")
555   :type '(choice (const :tag "nntp" nil)
556                  (string :tag "name")
557                  (sexp :tag "none" :format "%t" t)))
558
559 (defvar message-reply-buffer nil)
560 (defvar message-reply-headers nil)
561 (defvar message-newsreader nil)
562 (defvar message-mailer nil)
563 (defvar message-sent-message-via nil)
564 (defvar message-checksum nil)
565 (defvar message-send-actions nil
566   "A list of actions to be performed upon successful sending of a message.")
567 (defvar message-exit-actions nil
568   "A list of actions to be performed upon exiting after sending a message.")
569 (defvar message-kill-actions nil
570   "A list of actions to be performed before killing a message buffer.")
571 (defvar message-postpone-actions nil
572   "A list of actions to be performed after postponing a message.")
573
574 (define-widget 'message-header-lines 'text
575   "All header lines must be LFD terminated."
576   :format "%t:%n%v"
577   :valid-regexp "^\\'"
578   :error "All header lines must be newline terminated")
579
580 (defcustom message-default-headers ""
581   "*A string containing header lines to be inserted in outgoing messages.
582 It is inserted before you edit the message, so you can edit or delete
583 these lines."
584   :group 'message-headers
585   :type 'message-header-lines)
586
587 (defcustom message-default-mail-headers ""
588   "*A string of header lines to be inserted in outgoing mails."
589   :group 'message-headers
590   :group 'message-mail
591   :type 'message-header-lines)
592
593 (defcustom message-default-news-headers ""
594   "*A string of header lines to be inserted in outgoing news articles."
595   :group 'message-headers
596   :group 'message-news
597   :type 'message-header-lines)
598
599 ;; Note: could use /usr/ucb/mail instead of sendmail;
600 ;; options -t, and -v if not interactive.
601 (defcustom message-mailer-swallows-blank-line
602   (if (and (string-match "sparc-sun-sunos\\(\\'\\|[^5]\\)"
603                          system-configuration)
604            (file-readable-p "/etc/sendmail.cf")
605            (let ((buffer (get-buffer-create " *temp*")))
606              (unwind-protect
607                  (save-excursion
608                    (set-buffer buffer)
609                    (insert-file-contents "/etc/sendmail.cf")
610                    (goto-char (point-min))
611                    (let ((case-fold-search nil))
612                      (re-search-forward "^OR\\>" nil t)))
613                (kill-buffer buffer))))
614       ;; According to RFC822, "The field-name must be composed of printable
615       ;; ASCII characters (i. e., characters that have decimal values between
616       ;; 33 and 126, except colon)", i. e., any chars except ctl chars,
617       ;; space, or colon.
618       '(looking-at "[ \t]\\|[][!\"#$%&'()*+,-./0-9;<=>?@A-Z\\\\^_`a-z{|}~]+:"))
619   "*Set this non-nil if the system's mailer runs the header and body together.
620 \(This problem exists on Sunos 4 when sendmail is run in remote mode.)
621 The value should be an expression to test whether the problem will
622 actually occur."
623   :group 'message-sending
624   :type 'sexp)
625
626 ;;;###autoload
627 (define-mail-user-agent 'message-user-agent
628   'message-mail 'message-send-and-exit
629   'message-kill-buffer 'message-send-hook)
630
631 (defvar message-mh-deletable-headers '(Message-ID Date Lines Sender)
632   "If non-nil, delete the deletable headers before feeding to mh.")
633
634 (defvar message-send-method-alist
635   '((news message-news-p message-send-via-news)
636     (mail message-mail-p message-send-via-mail))
637   "Alist of ways to send outgoing messages.
638 Each element has the form
639
640   \(TYPE PREDICATE FUNCTION)
641
642 where TYPE is a symbol that names the method; PREDICATE is a function
643 called without any parameters to determine whether the message is
644 a message of type TYPE; and FUNCTION is a function to be called if
645 PREDICATE returns non-nil.  FUNCTION is called with one parameter --
646 the prefix.")
647
648 (defvar message-mail-alias-type 'abbrev
649   "*What alias expansion type to use in Message buffers.
650 The default is `abbrev', which uses mailabbrev.  nil switches
651 mail aliases off.")
652
653 (defcustom message-auto-save-directory
654   (nnheader-concat message-directory "drafts/")
655   "*Directory where Message auto-saves buffers if Gnus isn't running.
656 If nil, Message won't auto-save."
657   :group 'message-buffers
658   :type 'directory)
659
660 (defcustom message-buffer-naming-style 'unique
661   "*The way new message buffers are named.
662 Valid valued are `unique' and `unsent'."
663   :group 'message-buffers
664   :type '(choice (const :tag "unique" unique)
665                  (const :tag "unsent" unsent)))
666
667 (defcustom message-default-charset nil
668   "Default charset used in non-MULE XEmacsen."
669   :group 'message
670   :type 'symbol)
671
672 (defcustom message-dont-reply-to-names 
673   (and (boundp 'rmail-dont-reply-to-names) rmail-dont-reply-to-names)
674   "*A regexp specifying names to prune when doing wide replies.
675 A value of nil means exclude your own name only."
676   :group 'message
677   :type '(choice (const :tag "Yourself" nil)
678                  regexp))
679
680 ;;; Internal variables.
681 ;;; Well, not really internal.
682
683 (defvar message-mode-syntax-table
684   (let ((table (copy-syntax-table text-mode-syntax-table)))
685     (modify-syntax-entry ?% ". " table)
686     (modify-syntax-entry ?> ". " table)
687     (modify-syntax-entry ?< ". " table)
688     table)
689   "Syntax table used while in Message mode.")
690
691 (defvar message-mode-abbrev-table text-mode-abbrev-table
692   "Abbrev table used in Message mode buffers.
693 Defaults to `text-mode-abbrev-table'.")
694 (defgroup message-headers nil
695   "Message headers."
696   :link '(custom-manual "(message)Variables")
697   :group 'message)
698
699 (defface message-header-to-face
700   '((((class color)
701       (background dark))
702      (:foreground "green2" :bold t))
703     (((class color)
704       (background light))
705      (:foreground "MidnightBlue" :bold t))
706     (t
707      (:bold t :italic t)))
708   "Face used for displaying From headers."
709   :group 'message-faces)
710
711 (defface message-header-cc-face
712   '((((class color)
713       (background dark))
714      (:foreground "green4" :bold t))
715     (((class color)
716       (background light))
717      (:foreground "MidnightBlue"))
718     (t
719      (:bold t)))
720   "Face used for displaying Cc headers."
721   :group 'message-faces)
722
723 (defface message-header-subject-face
724   '((((class color)
725       (background dark))
726      (:foreground "green3"))
727     (((class color)
728       (background light))
729      (:foreground "navy blue" :bold t))
730     (t
731      (:bold t)))
732   "Face used for displaying subject headers."
733   :group 'message-faces)
734
735 (defface message-header-newsgroups-face
736   '((((class color)
737       (background dark))
738      (:foreground "yellow" :bold t :italic t))
739     (((class color)
740       (background light))
741      (:foreground "blue4" :bold t :italic t))
742     (t
743      (:bold t :italic t)))
744   "Face used for displaying newsgroups headers."
745   :group 'message-faces)
746
747 (defface message-header-other-face
748   '((((class color)
749       (background dark))
750      (:foreground "#b00000"))
751     (((class color)
752       (background light))
753      (:foreground "steel blue"))
754     (t
755      (:bold t :italic t)))
756   "Face used for displaying newsgroups headers."
757   :group 'message-faces)
758
759 (defface message-header-name-face
760   '((((class color)
761       (background dark))
762      (:foreground "DarkGreen"))
763     (((class color)
764       (background light))
765      (:foreground "cornflower blue"))
766     (t
767      (:bold t)))
768   "Face used for displaying header names."
769   :group 'message-faces)
770
771 (defface message-header-xheader-face
772   '((((class color)
773       (background dark))
774      (:foreground "blue"))
775     (((class color)
776       (background light))
777      (:foreground "blue"))
778     (t
779      (:bold t)))
780   "Face used for displaying X-Header headers."
781   :group 'message-faces)
782
783 (defface message-separator-face
784   '((((class color)
785       (background dark))
786      (:foreground "blue3"))
787     (((class color)
788       (background light))
789      (:foreground "brown"))
790     (t
791      (:bold t)))
792   "Face used for displaying the separator."
793   :group 'message-faces)
794
795 (defface message-cited-text-face
796   '((((class color)
797       (background dark))
798      (:foreground "red"))
799     (((class color)
800       (background light))
801      (:foreground "red"))
802     (t
803      (:bold t)))
804   "Face used for displaying cited text names."
805   :group 'message-faces)
806
807 (defface message-mml-face
808   '((((class color)
809       (background dark))
810      (:foreground "ForestGreen"))
811     (((class color)
812       (background light))
813      (:foreground "ForestGreen"))
814     (t
815      (:bold t)))
816   "Face used for displaying MML."
817   :group 'message-faces)
818
819 (defvar message-font-lock-keywords
820   (let* ((cite-prefix "A-Za-z")
821          (cite-suffix (concat cite-prefix "0-9_.@-"))
822          (content "[ \t]*\\(.+\\(\n[ \t].*\\)*\\)"))
823     `((,(concat "^\\([Tt]o:\\)" content)
824        (1 'message-header-name-face)
825        (2 'message-header-to-face nil t))
826       (,(concat "^\\(^[GBF]?[Cc][Cc]:\\|^[Rr]eply-[Tt]o:\\)" content)
827        (1 'message-header-name-face)
828        (2 'message-header-cc-face nil t))
829       (,(concat "^\\([Ss]ubject:\\)" content)
830        (1 'message-header-name-face)
831        (2 'message-header-subject-face nil t))
832       (,(concat "^\\([Nn]ewsgroups:\\|Followup-[Tt]o:\\)" content)
833        (1 'message-header-name-face)
834        (2 'message-header-newsgroups-face nil t))
835       (,(concat "^\\([A-Z][^: \n\t]+:\\)" content)
836        (1 'message-header-name-face)
837        (2 'message-header-other-face nil t))
838       (,(concat "^\\(X-[A-Za-z0-9-]+\\|In-Reply-To\\):" content)
839        (1 'message-header-name-face)
840        (2 'message-header-name-face))
841       ,@(if (and mail-header-separator
842                  (not (equal mail-header-separator "")))
843             `((,(concat "^\\(" (regexp-quote mail-header-separator) "\\)$")
844                1 'message-separator-face))
845           nil)
846       (,(concat "^[ \t]*"
847                 "\\([" cite-prefix "]+[" cite-suffix "]*\\)?"
848                 "[:>|}].*")
849        (0 'message-cited-text-face))
850       ("<#/?\\(multipart\\|part\\|external\\|mml\\).*>"
851        (0 'message-mml-face))))
852   "Additional expressions to highlight in Message mode.")
853
854 ;; XEmacs does it like this.  For Emacs, we have to set the
855 ;; `font-lock-defaults' buffer-local variable.
856 (put 'message-mode 'font-lock-defaults '(message-font-lock-keywords t))
857
858 (defvar message-face-alist
859   '((bold . bold-region)
860     (underline . underline-region)
861     (default . (lambda (b e)
862                  (unbold-region b e)
863                  (ununderline-region b e))))
864   "Alist of mail and news faces for facemenu.
865 The cdr of ech entry is a function for applying the face to a region.")
866
867 (defcustom message-send-hook nil
868   "Hook run before sending messages."
869   :group 'message-various
870   :options '(ispell-message)
871   :type 'hook)
872
873 (defcustom message-send-mail-hook nil
874   "Hook run before sending mail messages."
875   :group 'message-various
876   :type 'hook)
877
878 (defcustom message-send-news-hook nil
879   "Hook run before sending news messages."
880   :group 'message-various
881   :type 'hook)
882
883 (defcustom message-sent-hook nil
884   "Hook run after sending messages."
885   :group 'message-various
886   :type 'hook)
887
888 (defvar message-send-coding-system 'binary
889   "Coding system to encode outgoing mail.")
890
891 (defvar message-draft-coding-system
892   mm-auto-save-coding-system
893   "Coding system to compose mail.")
894
895 (defcustom message-send-mail-partially-limit 1000000
896   "The limitation of messages sent as message/partial.
897 The lower bound of message size in characters, beyond which the message 
898 should be sent in several parts. If it is nil, the size is unlimited."
899   :group 'message-buffers
900   :type '(choice (const :tag "unlimited" nil)
901                  (integer 1000000)))
902
903 ;;; Internal variables.
904
905 (defvar message-buffer-list nil)
906 (defvar message-this-is-news nil)
907 (defvar message-this-is-mail nil)
908 (defvar message-draft-article nil)
909 (defvar message-mime-part nil)
910 (defvar message-posting-charset nil)
911
912 ;; Byte-compiler warning
913 (defvar gnus-active-hashtb)
914 (defvar gnus-read-active-file)
915
916 ;;; Regexp matching the delimiter of messages in UNIX mail format
917 ;;; (UNIX From lines), minus the initial ^.  It should be a copy
918 ;;; of rmail.el's rmail-unix-mail-delimiter.
919 (defvar message-unix-mail-delimiter
920   (let ((time-zone-regexp
921          (concat "\\([A-Z]?[A-Z]?[A-Z][A-Z]\\( DST\\)?"
922                  "\\|[-+]?[0-9][0-9][0-9][0-9]"
923                  "\\|"
924                  "\\) *")))
925     (concat
926      "From "
927
928      ;; Many things can happen to an RFC 822 mailbox before it is put into
929      ;; a `From' line.  The leading phrase can be stripped, e.g.
930      ;; `Joe <@w.x:joe@y.z>' -> `<@w.x:joe@y.z>'.  The <> can be stripped, e.g.
931      ;; `<@x.y:joe@y.z>' -> `@x.y:joe@y.z'.  Everything starting with a CRLF
932      ;; can be removed, e.g.
933      ;;         From: joe@y.z (Joe      K
934      ;;                 User)
935      ;; can yield `From joe@y.z (Joe    K Fri Mar 22 08:11:15 1996', and
936      ;;         From: Joe User
937      ;;                 <joe@y.z>
938      ;; can yield `From Joe User Fri Mar 22 08:11:15 1996'.
939      ;; The mailbox can be removed or be replaced by white space, e.g.
940      ;;         From: "Joe User"{space}{tab}
941      ;;                 <joe@y.z>
942      ;; can yield `From {space}{tab} Fri Mar 22 08:11:15 1996',
943      ;; where {space} and {tab} represent the Ascii space and tab characters.
944      ;; We want to match the results of any of these manglings.
945      ;; The following regexp rejects names whose first characters are
946      ;; obviously bogus, but after that anything goes.
947      "\\([^\0-\b\n-\r\^?].*\\)? "
948
949      ;; The time the message was sent.
950      "\\([^\0-\r \^?]+\\) +"            ; day of the week
951      "\\([^\0-\r \^?]+\\) +"            ; month
952      "\\([0-3]?[0-9]\\) +"              ; day of month
953      "\\([0-2][0-9]:[0-5][0-9]\\(:[0-6][0-9]\\)?\\) *" ; time of day
954
955      ;; Perhaps a time zone, specified by an abbreviation, or by a
956      ;; numeric offset.
957      time-zone-regexp
958
959      ;; The year.
960      " \\([0-9][0-9]+\\) *"
961
962      ;; On some systems the time zone can appear after the year, too.
963      time-zone-regexp
964
965      ;; Old uucp cruft.
966      "\\(remote from .*\\)?"
967
968      "\n"))
969   "Regexp matching the delimiter of messages in UNIX mail format.")
970
971 (defvar message-unsent-separator
972   (concat "^ *---+ +Unsent message follows +---+ *$\\|"
973           "^ *---+ +Returned message +---+ *$\\|"
974           "^Start of returned message$\\|"
975           "^ *---+ +Original message +---+ *$\\|"
976           "^ *--+ +begin message +--+ *$\\|"
977           "^ *---+ +Original message follows +---+ *$\\|"
978           "^ *---+ +Undelivered message follows +---+ *$\\|"
979           "^|? *---+ +Message text follows: +---+ *|?$")
980   "A regexp that matches the separator before the text of a failed message.")
981
982 (defvar message-header-format-alist
983   `((Newsgroups)
984     (To . message-fill-address)
985     (Cc . message-fill-address)
986     (Subject)
987     (In-Reply-To)
988     (Fcc)
989     (Bcc)
990     (Date)
991     (Organization)
992     (Distribution)
993     (Lines)
994     (Expires)
995     (Message-ID)
996     (References . message-shorten-references)
997     (User-Agent))
998   "Alist used for formatting headers.")
999
1000 (eval-and-compile
1001   (autoload 'message-setup-toolbar "messagexmas")
1002   (autoload 'mh-new-draft-name "mh-comp")
1003   (autoload 'mh-send-letter "mh-comp")
1004   (autoload 'gnus-point-at-eol "gnus-util")
1005   (autoload 'gnus-point-at-bol "gnus-util")
1006   (autoload 'gnus-output-to-rmail "gnus-util")
1007   (autoload 'gnus-output-to-mail "gnus-util")
1008   (autoload 'mail-abbrev-in-expansion-header-p "mailabbrev")
1009   (autoload 'nndraft-request-associate-buffer "nndraft")
1010   (autoload 'nndraft-request-expire-articles "nndraft")
1011   (autoload 'gnus-open-server "gnus-int")
1012   (autoload 'gnus-request-post "gnus-int")
1013   (autoload 'gnus-alive-p "gnus-util")
1014   (autoload 'gnus-group-name-charset "gnus-group")
1015   (autoload 'rmail-output "rmail"))
1016
1017 \f
1018
1019 ;;;
1020 ;;; Utility functions.
1021 ;;;
1022
1023 (defmacro message-y-or-n-p (question show &rest text)
1024   "Ask QUESTION, displaying the rest of the arguments in a temp. buffer if SHOW"
1025   `(message-talkative-question 'y-or-n-p ,question ,show ,@text))
1026
1027 ;; Delete the current line (and the next N lines.);
1028 (defmacro message-delete-line (&optional n)
1029   `(delete-region (progn (beginning-of-line) (point))
1030                   (progn (forward-line ,(or n 1)) (point))))
1031
1032 (defun message-unquote-tokens (elems)
1033   "Remove double quotes (\") from strings in list."
1034   (mapcar (lambda (item)
1035             (while (string-match "^\\(.*\\)\"\\(.*\\)$" item)
1036               (setq item (concat (match-string 1 item) 
1037                                  (match-string 2 item))))
1038             item)
1039           elems))
1040
1041 (defun message-tokenize-header (header &optional separator)
1042   "Split HEADER into a list of header elements.
1043 SEPARATOR is a string of characters to be used as separators.  \",\"
1044 is used by default."
1045   (if (not header)
1046       nil
1047     (let ((regexp (format "[%s]+" (or separator ",")))
1048           (beg 1)
1049           (first t)
1050           quoted elems paren)
1051       (save-excursion
1052         (message-set-work-buffer)
1053         (insert header)
1054         (goto-char (point-min))
1055         (while (not (eobp))
1056           (if first
1057               (setq first nil)
1058             (forward-char 1))
1059           (cond ((and (> (point) beg)
1060                       (or (eobp)
1061                           (and (looking-at regexp)
1062                                (not quoted)
1063                                (not paren))))
1064                  (push (buffer-substring beg (point)) elems)
1065                  (setq beg (match-end 0)))
1066                 ((eq (char-after) ?\")
1067                  (setq quoted (not quoted)))
1068                 ((and (eq (char-after) ?\()
1069                       (not quoted))
1070                  (setq paren t))
1071                 ((and (eq (char-after) ?\))
1072                       (not quoted))
1073                  (setq paren nil))))
1074         (nreverse elems)))))
1075
1076 (defun message-mail-file-mbox-p (file)
1077   "Say whether FILE looks like a Unix mbox file."
1078   (when (and (file-exists-p file)
1079              (file-readable-p file)
1080              (file-regular-p file))
1081     (with-temp-buffer
1082       (nnheader-insert-file-contents file)
1083       (goto-char (point-min))
1084       (looking-at message-unix-mail-delimiter))))
1085
1086 (defun message-fetch-field (header &optional not-all)
1087   "The same as `mail-fetch-field', only remove all newlines."
1088   (let* ((inhibit-point-motion-hooks t)
1089          (case-fold-search t)
1090          (value (mail-fetch-field header nil (not not-all))))
1091     (when value
1092       (while (string-match "\n[\t ]+" value)
1093         (setq value (replace-match " " t t value)))
1094       (set-text-properties 0 (length value) nil value)
1095       value)))
1096
1097 (defun message-narrow-to-field ()
1098   "Narrow the buffer to the header on the current line."
1099   (beginning-of-line)
1100   (narrow-to-region
1101    (point)
1102    (progn
1103      (forward-line 1)
1104      (if (re-search-forward "^[^ \n\t]" nil t)
1105          (progn
1106            (beginning-of-line)
1107            (point))
1108        (point-max))))
1109   (goto-char (point-min)))
1110
1111 (defun message-add-header (&rest headers)
1112   "Add the HEADERS to the message header, skipping those already present."
1113   (while headers
1114     (let (hclean)
1115       (unless (string-match "^\\([^:]+\\):[ \t]*[^ \t]" (car headers))
1116         (error "Invalid header `%s'" (car headers)))
1117       (setq hclean (match-string 1 (car headers)))
1118       (save-restriction
1119         (message-narrow-to-headers)
1120         (unless (re-search-forward (concat "^" (regexp-quote hclean) ":") nil t)
1121           (insert (car headers) ?\n))))
1122     (setq headers (cdr headers))))
1123
1124
1125 (defun message-fetch-reply-field (header)
1126   "Fetch FIELD from the message we're replying to."
1127   (when (and message-reply-buffer
1128              (buffer-name message-reply-buffer))
1129     (save-excursion
1130       (set-buffer message-reply-buffer)
1131       (message-fetch-field header))))
1132
1133 (defun message-set-work-buffer ()
1134   (if (get-buffer " *message work*")
1135       (progn
1136         (set-buffer " *message work*")
1137         (erase-buffer))
1138     (set-buffer (get-buffer-create " *message work*"))
1139     (kill-all-local-variables)
1140     (mm-enable-multibyte)))
1141
1142 (defun message-functionp (form)
1143   "Return non-nil if FORM is funcallable."
1144   (or (and (symbolp form) (fboundp form))
1145       (and (listp form) (eq (car form) 'lambda))
1146       (byte-code-function-p form)))
1147
1148 (defun message-strip-list-identifiers (subject)
1149   "Remove list identifiers in `gnus-list-identifiers'."
1150   (require 'gnus-sum)                   ; for gnus-list-identifiers
1151   (let ((regexp (if (stringp gnus-list-identifiers)
1152                     gnus-list-identifiers
1153                   (mapconcat 'identity gnus-list-identifiers " *\\|"))))
1154     (if (string-match (concat "\\(\\(\\(Re: +\\)?\\(" regexp 
1155                                 " *\\)\\)+\\(Re: +\\)?\\)") subject)
1156         (concat (substring subject 0 (match-beginning 1))
1157                 (or (match-string 3 subject)
1158                     (match-string 5 subject))
1159                 (substring subject
1160                            (match-end 1)))
1161       subject)))
1162
1163 (defun message-strip-subject-re (subject)
1164   "Remove \"Re:\" from subject lines."
1165   (if (string-match message-subject-re-regexp subject)
1166       (substring subject (match-end 0))
1167     subject))
1168
1169 (defun message-remove-header (header &optional is-regexp first reverse)
1170   "Remove HEADER in the narrowed buffer.
1171 If REGEXP, HEADER is a regular expression.
1172 If FIRST, only remove the first instance of the header.
1173 Return the number of headers removed."
1174   (goto-char (point-min))
1175   (let ((regexp (if is-regexp header (concat "^" (regexp-quote header) ":")))
1176         (number 0)
1177         (case-fold-search t)
1178         last)
1179     (while (and (not (eobp))
1180                 (not last))
1181       (if (if reverse
1182               (not (looking-at regexp))
1183             (looking-at regexp))
1184           (progn
1185             (incf number)
1186             (when first
1187               (setq last t))
1188             (delete-region
1189              (point)
1190              ;; There might be a continuation header, so we have to search
1191              ;; until we find a new non-continuation line.
1192              (progn
1193                (forward-line 1)
1194                (if (re-search-forward "^[^ \t]" nil t)
1195                    (goto-char (match-beginning 0))
1196                  (point-max)))))
1197         (forward-line 1)
1198         (if (re-search-forward "^[^ \t]" nil t)
1199             (goto-char (match-beginning 0))
1200           (goto-char (point-max)))))
1201     number))
1202
1203 (defun message-remove-first-header (header)
1204   "Remove the first instance of HEADER if there is more than one."
1205   (let ((count 0)
1206         (regexp (concat "^" (regexp-quote header) ":")))
1207     (save-excursion
1208       (goto-char (point-min))
1209       (while (re-search-forward regexp nil t)
1210         (incf count)))
1211     (while (> count 1)
1212       (message-remove-header header nil t)
1213       (decf count))))
1214
1215 (defun message-narrow-to-headers ()
1216   "Narrow the buffer to the head of the message."
1217   (widen)
1218   (narrow-to-region
1219    (goto-char (point-min))
1220    (if (re-search-forward
1221         (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
1222        (match-beginning 0)
1223      (point-max)))
1224   (goto-char (point-min)))
1225
1226 (defun message-narrow-to-head ()
1227   "Narrow the buffer to the head of the message.
1228 Point is left at the beginning of the narrowed-to region."
1229   (widen)
1230   (narrow-to-region
1231    (goto-char (point-min))
1232    (if (search-forward "\n\n" nil 1)
1233        (1- (point))
1234      (point-max)))
1235   (goto-char (point-min)))
1236
1237 (defun message-narrow-to-headers-or-head ()
1238   "Narrow the buffer to the head of the message."
1239   (widen)
1240   (narrow-to-region
1241    (goto-char (point-min))
1242    (cond
1243     ((re-search-forward
1244       (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
1245      (match-beginning 0))
1246     ((search-forward "\n\n" nil t)
1247      (1- (point)))
1248     (t
1249      (point-max))))
1250   (goto-char (point-min)))
1251
1252 (defun message-news-p ()
1253   "Say whether the current buffer contains a news message."
1254   (and (not message-this-is-mail)
1255        (or message-this-is-news
1256            (save-excursion
1257              (save-restriction
1258                (message-narrow-to-headers)
1259                (and (message-fetch-field "newsgroups")
1260                     (not (message-fetch-field "posted-to"))))))))
1261
1262 (defun message-mail-p ()
1263   "Say whether the current buffer contains a mail message."
1264   (and (not message-this-is-news)
1265        (or message-this-is-mail
1266            (save-excursion
1267              (save-restriction
1268                (message-narrow-to-headers)
1269                (or (message-fetch-field "to")
1270                    (message-fetch-field "cc")
1271                    (message-fetch-field "bcc")))))))
1272
1273 (defun message-next-header ()
1274   "Go to the beginning of the next header."
1275   (beginning-of-line)
1276   (or (eobp) (forward-char 1))
1277   (not (if (re-search-forward "^[^ \t]" nil t)
1278            (beginning-of-line)
1279          (goto-char (point-max)))))
1280
1281 (defun message-sort-headers-1 ()
1282   "Sort the buffer as headers using `message-rank' text props."
1283   (goto-char (point-min))
1284   (require 'sort)
1285   (sort-subr
1286    nil 'message-next-header
1287    (lambda ()
1288      (message-next-header)
1289      (unless (bobp)
1290        (forward-char -1)))
1291    (lambda ()
1292      (or (get-text-property (point) 'message-rank)
1293          10000))))
1294
1295 (defun message-sort-headers ()
1296   "Sort the headers of the current message according to `message-header-format-alist'."
1297   (interactive)
1298   (save-excursion
1299     (save-restriction
1300       (let ((max (1+ (length message-header-format-alist)))
1301             rank)
1302         (message-narrow-to-headers)
1303         (while (re-search-forward "^[^ \n]+:" nil t)
1304           (put-text-property
1305            (match-beginning 0) (1+ (match-beginning 0))
1306            'message-rank
1307            (if (setq rank (length (memq (assq (intern (buffer-substring
1308                                                        (match-beginning 0)
1309                                                        (1- (match-end 0))))
1310                                               message-header-format-alist)
1311                                         message-header-format-alist)))
1312                (- max rank)
1313              (1+ max)))))
1314       (message-sort-headers-1))))
1315
1316 \f
1317
1318 ;;;
1319 ;;; Message mode
1320 ;;;
1321
1322 ;;; Set up keymap.
1323
1324 (defvar message-mode-map nil)
1325
1326 (unless message-mode-map
1327   (setq message-mode-map (make-keymap))
1328   (set-keymap-parent message-mode-map text-mode-map)
1329   (define-key message-mode-map "\C-c?" 'describe-mode)
1330
1331   (define-key message-mode-map "\C-c\C-f\C-t" 'message-goto-to)
1332   (define-key message-mode-map "\C-c\C-f\C-b" 'message-goto-bcc)
1333   (define-key message-mode-map "\C-c\C-f\C-w" 'message-goto-fcc)
1334   (define-key message-mode-map "\C-c\C-f\C-c" 'message-goto-cc)
1335   (define-key message-mode-map "\C-c\C-f\C-s" 'message-goto-subject)
1336   (define-key message-mode-map "\C-c\C-f\C-r" 'message-goto-reply-to)
1337   (define-key message-mode-map "\C-c\C-f\C-n" 'message-goto-newsgroups)
1338   (define-key message-mode-map "\C-c\C-f\C-d" 'message-goto-distribution)
1339   (define-key message-mode-map "\C-c\C-f\C-f" 'message-goto-followup-to)
1340   (define-key message-mode-map "\C-c\C-f\C-k" 'message-goto-keywords)
1341   (define-key message-mode-map "\C-c\C-f\C-u" 'message-goto-summary)
1342   (define-key message-mode-map "\C-c\C-b" 'message-goto-body)
1343   (define-key message-mode-map "\C-c\C-i" 'message-goto-signature)
1344
1345   (define-key message-mode-map "\C-c\C-t" 'message-insert-to)
1346   (define-key message-mode-map "\C-c\C-n" 'message-insert-newsgroups)
1347
1348   (define-key message-mode-map "\C-c\C-y" 'message-yank-original)
1349   (define-key message-mode-map "\C-c\M-\C-y" 'message-yank-buffer)
1350   (define-key message-mode-map "\C-c\C-q" 'message-fill-yanked-message)
1351   (define-key message-mode-map "\C-c\C-w" 'message-insert-signature)
1352   (define-key message-mode-map "\C-c\M-h" 'message-insert-headers)
1353   (define-key message-mode-map "\C-c\C-r" 'message-caesar-buffer-body)
1354   (define-key message-mode-map "\C-c\C-o" 'message-sort-headers)
1355   (define-key message-mode-map "\C-c\M-r" 'message-rename-buffer)
1356
1357   (define-key message-mode-map "\C-c\C-c" 'message-send-and-exit)
1358   (define-key message-mode-map "\C-c\C-s" 'message-send)
1359   (define-key message-mode-map "\C-c\C-k" 'message-kill-buffer)
1360   (define-key message-mode-map "\C-c\C-d" 'message-dont-send)
1361
1362   (define-key message-mode-map "\C-c\C-e" 'message-elide-region)
1363   (define-key message-mode-map "\C-c\C-v" 'message-delete-not-region)
1364   (define-key message-mode-map "\C-c\C-z" 'message-kill-to-signature)
1365   (define-key message-mode-map "\M-\r" 'message-newline-and-reformat)
1366
1367   (define-key message-mode-map "\C-c\C-a" 'mml-attach-file)
1368
1369   (define-key message-mode-map "\t" 'message-tab))
1370
1371 (easy-menu-define
1372  message-mode-menu message-mode-map "Message Menu."
1373  '("Message"
1374    ["Sort Headers" message-sort-headers t]
1375    ["Yank Original" message-yank-original t]
1376    ["Fill Yanked Message" message-fill-yanked-message t]
1377    ["Insert Signature" message-insert-signature t]
1378    ["Caesar (rot13) Message" message-caesar-buffer-body t]
1379    ["Caesar (rot13) Region" message-caesar-region (mark t)]
1380    ["Elide Region" message-elide-region (mark t)]
1381    ["Delete Outside Region" message-delete-not-region (mark t)]
1382    ["Kill To Signature" message-kill-to-signature t]
1383    ["Newline and Reformat" message-newline-and-reformat t]
1384    ["Rename buffer" message-rename-buffer t]
1385    ["Spellcheck" ispell-message t]
1386    ["Attach file as MIME" mml-attach-file t]
1387    "----"
1388    ["Send Message" message-send-and-exit t]
1389    ["Abort Message" message-dont-send t]
1390    ["Kill Message" message-kill-buffer t]))
1391
1392 (easy-menu-define
1393  message-mode-field-menu message-mode-map ""
1394  '("Field"
1395    ["Fetch To" message-insert-to t]
1396    ["Fetch Newsgroups" message-insert-newsgroups t]
1397    "----"
1398    ["To" message-goto-to t]
1399    ["Subject" message-goto-subject t]
1400    ["Cc" message-goto-cc t]
1401    ["Reply-To" message-goto-reply-to t]
1402    ["Summary" message-goto-summary t]
1403    ["Keywords" message-goto-keywords t]
1404    ["Newsgroups" message-goto-newsgroups t]
1405    ["Followup-To" message-goto-followup-to t]
1406    ["Distribution" message-goto-distribution t]
1407    ["Body" message-goto-body t]
1408    ["Signature" message-goto-signature t]))
1409
1410 (defvar facemenu-add-face-function)
1411 (defvar facemenu-remove-face-function)
1412
1413 ;;;###autoload
1414 (defun message-mode ()
1415   "Major mode for editing mail and news to be sent.
1416 Like Text Mode but with these additional commands:
1417 C-c C-s  message-send (send the message)    C-c C-c  message-send-and-exit
1418 C-c C-d  Pospone sending the message        C-c C-k  Kill the message
1419 C-c C-f  move to a header field (and create it if there isn't):
1420          C-c C-f C-t  move to To        C-c C-f C-s  move to Subject
1421          C-c C-f C-c  move to Cc        C-c C-f C-b  move to Bcc
1422          C-c C-f C-w  move to Fcc       C-c C-f C-r  move to Reply-To
1423          C-c C-f C-u  move to Summary   C-c C-f C-n  move to Newsgroups
1424          C-c C-f C-k  move to Keywords  C-c C-f C-d  move to Distribution
1425          C-c C-f C-f  move to Followup-To
1426 C-c C-t  message-insert-to (add a To header to a news followup)
1427 C-c C-n  message-insert-newsgroups (add a Newsgroup header to a news reply)
1428 C-c C-b  message-goto-body (move to beginning of message text).
1429 C-c C-i  message-goto-signature (move to the beginning of the signature).
1430 C-c C-w  message-insert-signature (insert `message-signature-file' file).
1431 C-c C-y  message-yank-original (insert current message, if any).
1432 C-c C-q  message-fill-yanked-message (fill what was yanked).
1433 C-c C-e  message-elide-region (elide the text between point and mark).
1434 C-c C-v  message-delete-not-region (remove the text outside the region).
1435 C-c C-z  message-kill-to-signature (kill the text up to the signature).
1436 C-c C-r  message-caesar-buffer-body (rot13 the message body).
1437 C-c C-a  mml-attach-file (attach a file as MIME).
1438 M-RET    message-newline-and-reformat (break the line and reformat)."
1439   (interactive)
1440   (if (local-variable-p 'mml-buffer-list (current-buffer))
1441       (mml-destroy-buffers))
1442   (kill-all-local-variables)
1443   (set (make-local-variable 'message-reply-buffer) nil)
1444   (make-local-variable 'message-send-actions)
1445   (make-local-variable 'message-exit-actions)
1446   (make-local-variable 'message-kill-actions)
1447   (make-local-variable 'message-postpone-actions)
1448   (make-local-variable 'message-draft-article)
1449   (make-local-hook 'kill-buffer-hook)
1450   (set-syntax-table message-mode-syntax-table)
1451   (use-local-map message-mode-map)
1452   (setq local-abbrev-table message-mode-abbrev-table)
1453   (setq major-mode 'message-mode)
1454   (setq mode-name "Message")
1455   (setq buffer-offer-save t)
1456   (make-local-variable 'facemenu-add-face-function)
1457   (make-local-variable 'facemenu-remove-face-function)
1458   (setq facemenu-add-face-function
1459         (lambda (face end)
1460           (let ((face-fun (cdr (assq face message-face-alist))))
1461             (if face-fun
1462                 (funcall face-fun (point) end)
1463               (error "Face %s not configured for %s mode" face mode-name)))
1464           "")
1465         facemenu-remove-face-function t)
1466   (make-local-variable 'paragraph-separate)
1467   (make-local-variable 'paragraph-start)
1468   ;; `-- ' precedes the signature.  `-----' appears at the start of the
1469   ;; lines that delimit forwarded messages.
1470   ;; Lines containing just >= 3 dashes, perhaps after whitespace,
1471   ;; are also sometimes used and should be separators.
1472   (setq paragraph-start
1473         (concat (regexp-quote mail-header-separator)
1474                 "$\\|[ \t]*[a-z0-9A-Z]*>+[ \t]*$\\|[ \t]*$\\|"
1475                 "-- $\\|---+$\\|"
1476                 page-delimiter
1477                 ;;!!! Uhm... shurely this can't be right?
1478                 "[> " (regexp-quote message-yank-prefix) "]+$"))
1479   (setq paragraph-separate paragraph-start)
1480   (make-local-variable 'message-reply-headers)
1481   (setq message-reply-headers nil)
1482   (make-local-variable 'message-newsreader)
1483   (make-local-variable 'message-mailer)
1484   (make-local-variable 'message-post-method)
1485   (set (make-local-variable 'message-sent-message-via) nil)
1486   (set (make-local-variable 'message-checksum) nil)
1487   (set (make-local-variable 'message-mime-part) 0)
1488   ;;(when (fboundp 'mail-hist-define-keys)
1489   ;;  (mail-hist-define-keys))
1490   (if (featurep 'xemacs)
1491       (message-setup-toolbar)
1492     (set (make-local-variable 'font-lock-defaults)
1493          '(message-font-lock-keywords t)))
1494   (easy-menu-add message-mode-menu message-mode-map)
1495   (easy-menu-add message-mode-field-menu message-mode-map)
1496   ;; Allow mail alias things.
1497   (when (eq message-mail-alias-type 'abbrev)
1498     (if (fboundp 'mail-abbrevs-setup)
1499         (mail-abbrevs-setup)
1500       (mail-aliases-setup)))
1501   (message-set-auto-save-file-name)
1502   (make-local-variable 'adaptive-fill-regexp)
1503   (setq adaptive-fill-regexp
1504         (concat "[ \t]*[-a-z0-9A-Z]*\\(>[ \t]*\\)+[ \t]*\\|" adaptive-fill-regexp))
1505   (unless (boundp 'adaptive-fill-first-line-regexp)
1506     (setq adaptive-fill-first-line-regexp nil))
1507   (make-local-variable 'adaptive-fill-first-line-regexp)
1508   (setq adaptive-fill-first-line-regexp
1509         (concat "[ \t]*[-a-z0-9A-Z]*\\(>[ \t]*\\)+[ \t]*\\|"
1510                 adaptive-fill-first-line-regexp))
1511   (make-local-variable 'auto-fill-inhibit-regexp)
1512   (setq auto-fill-inhibit-regexp "^[A-Z][^: \n\t]+:")
1513   (mm-enable-multibyte)
1514   (make-local-variable 'indent-tabs-mode) ;Turn off tabs for indentation.
1515   (setq indent-tabs-mode nil)
1516   (mml-mode)
1517   (run-hooks 'text-mode-hook 'message-mode-hook))
1518
1519 \f
1520
1521 ;;;
1522 ;;; Message mode commands
1523 ;;;
1524
1525 ;;; Movement commands
1526
1527 (defun message-goto-to ()
1528   "Move point to the To header."
1529   (interactive)
1530   (message-position-on-field "To"))
1531
1532 (defun message-goto-subject ()
1533   "Move point to the Subject header."
1534   (interactive)
1535   (message-position-on-field "Subject"))
1536
1537 (defun message-goto-cc ()
1538   "Move point to the Cc header."
1539   (interactive)
1540   (message-position-on-field "Cc" "To"))
1541
1542 (defun message-goto-bcc ()
1543   "Move point to the Bcc  header."
1544   (interactive)
1545   (message-position-on-field "Bcc" "Cc" "To"))
1546
1547 (defun message-goto-fcc ()
1548   "Move point to the Fcc header."
1549   (interactive)
1550   (message-position-on-field "Fcc" "To" "Newsgroups"))
1551
1552 (defun message-goto-reply-to ()
1553   "Move point to the Reply-To header."
1554   (interactive)
1555   (message-position-on-field "Reply-To" "Subject"))
1556
1557 (defun message-goto-newsgroups ()
1558   "Move point to the Newsgroups header."
1559   (interactive)
1560   (message-position-on-field "Newsgroups"))
1561
1562 (defun message-goto-distribution ()
1563   "Move point to the Distribution header."
1564   (interactive)
1565   (message-position-on-field "Distribution"))
1566
1567 (defun message-goto-followup-to ()
1568   "Move point to the Followup-To header."
1569   (interactive)
1570   (message-position-on-field "Followup-To" "Newsgroups"))
1571
1572 (defun message-goto-keywords ()
1573   "Move point to the Keywords header."
1574   (interactive)
1575   (message-position-on-field "Keywords" "Subject"))
1576
1577 (defun message-goto-summary ()
1578   "Move point to the Summary header."
1579   (interactive)
1580   (message-position-on-field "Summary" "Subject"))
1581
1582 (defun message-goto-body ()
1583   "Move point to the beginning of the message body."
1584   (interactive)
1585   (if (looking-at "[ \t]*\n") (expand-abbrev))
1586   (goto-char (point-min))
1587   (or (search-forward (concat "\n" mail-header-separator "\n") nil t)
1588       (search-forward "\n\n" nil t)))
1589
1590 (defun message-goto-eoh ()
1591   "Move point to the end of the headers."
1592   (interactive)
1593   (message-goto-body)
1594   (forward-line -1))
1595
1596 (defun message-goto-signature ()
1597   "Move point to the beginning of the message signature.
1598 If there is no signature in the article, go to the end and
1599 return nil."
1600   (interactive)
1601   (goto-char (point-min))
1602   (if (re-search-forward message-signature-separator nil t)
1603       (forward-line 1)
1604     (goto-char (point-max))
1605     nil))
1606
1607 \f
1608
1609 (defun message-insert-to (&optional force)
1610   "Insert a To header that points to the author of the article being replied to.
1611 If the original author requested not to be sent mail, the function signals
1612 an error.
1613 With the prefix argument FORCE, insert the header anyway."
1614   (interactive "P")
1615   (let ((co (message-fetch-reply-field "mail-copies-to")))
1616     (when (and (null force)
1617                co
1618                (or (equal (downcase co) "never")
1619                    (equal (downcase co) "nobody")))
1620       (error "The user has requested not to have copies sent via mail")))
1621   (when (and (message-position-on-field "To")
1622              (mail-fetch-field "to")
1623              (not (string-match "\\` *\\'" (mail-fetch-field "to"))))
1624     (insert ", "))
1625   (insert (or (message-fetch-reply-field "reply-to")
1626               (message-fetch-reply-field "from") "")))
1627
1628 (defun message-widen-reply ()
1629   "Widen the reply to include maximum recipients."
1630   (interactive)
1631   (let ((follow-to
1632          (and message-reply-buffer
1633               (buffer-name message-reply-buffer)
1634               (save-excursion
1635                 (set-buffer message-reply-buffer)
1636                 (message-get-reply-headers t)))))
1637     (save-excursion
1638       (save-restriction
1639         (message-narrow-to-headers)
1640         (dolist (elem follow-to)
1641           (message-remove-header (symbol-name (car elem)))
1642           (goto-char (point-min))
1643           (insert (symbol-name (car elem)) ": "
1644                   (cdr elem) "\n"))))))
1645
1646 (defun message-insert-newsgroups ()
1647   "Insert the Newsgroups header from the article being replied to."
1648   (interactive)
1649   (when (and (message-position-on-field "Newsgroups")
1650              (mail-fetch-field "newsgroups")
1651              (not (string-match "\\` *\\'" (mail-fetch-field "newsgroups"))))
1652     (insert ","))
1653   (insert (or (message-fetch-reply-field "newsgroups") "")))
1654
1655 \f
1656
1657 ;;; Various commands
1658
1659 (defun message-delete-not-region (beg end)
1660   "Delete everything in the body of the current message that is outside of the region."
1661   (interactive "r")
1662   (save-excursion
1663     (goto-char end)
1664     (delete-region (point) (if (not (message-goto-signature))
1665                                (point)
1666                              (forward-line -2)
1667                              (point)))
1668     (insert "\n")
1669     (goto-char beg)
1670     (delete-region beg (progn (message-goto-body)
1671                               (forward-line 2)
1672                               (point))))
1673   (when (message-goto-signature)
1674     (forward-line -2)))
1675
1676 (defun message-kill-to-signature ()
1677   "Deletes all text up to the signature."
1678   (interactive)
1679   (let ((point (point)))
1680     (message-goto-signature)
1681     (unless (eobp)
1682       (forward-line -2))
1683     (kill-region point (point))
1684     (unless (bolp)
1685       (insert "\n"))))
1686
1687 (defun message-newline-and-reformat ()
1688   "Insert four newlines, and then reformat if inside quoted text."
1689   (interactive)
1690   (let ((prefix "[]>»|:}+ \t]*")
1691         (supercite-thing "[-._a-zA-Z0-9]*[>]+[ \t]*")
1692         quoted point)
1693     (unless (bolp)
1694       (save-excursion
1695         (beginning-of-line)
1696         (when (looking-at (concat prefix
1697                                   supercite-thing))
1698           (setq quoted (match-string 0))))
1699       (insert "\n"))
1700     (setq point (point))
1701     (insert "\n\n\n")
1702     (delete-region (point) (re-search-forward "[ \t]*"))
1703     (when quoted
1704       (insert quoted))
1705     (fill-paragraph nil)
1706     (goto-char point)
1707     (forward-line 1)))
1708
1709 (defun message-insert-signature (&optional force)
1710   "Insert a signature.  See documentation for the `message-signature' variable."
1711   (interactive (list 0))
1712   (let* ((signature
1713           (cond
1714            ((and (null message-signature)
1715                  (eq force 0))
1716             (save-excursion
1717               (goto-char (point-max))
1718               (not (re-search-backward message-signature-separator nil t))))
1719            ((and (null message-signature)
1720                  force)
1721             t)
1722            ((message-functionp message-signature)
1723             (funcall message-signature))
1724            ((listp message-signature)
1725             (eval message-signature))
1726            (t message-signature)))
1727          (signature
1728           (cond ((stringp signature)
1729                  signature)
1730                 ((and (eq t signature)
1731                       message-signature-file
1732                       (file-exists-p message-signature-file))
1733                  signature))))
1734     (when signature
1735       (goto-char (point-max))
1736       ;; Insert the signature.
1737       (unless (bolp)
1738         (insert "\n"))
1739       (insert "\n-- \n")
1740       (if (eq signature t)
1741           (insert-file-contents message-signature-file)
1742         (insert signature))
1743       (goto-char (point-max))
1744       (or (bolp) (insert "\n")))))
1745
1746 (defun message-elide-region (b e)
1747   "Elide the text between point and mark.
1748 An ellipsis (from `message-elide-ellipsis') will be inserted where the
1749 text was killed."
1750   (interactive "r")
1751   (kill-region b e)
1752   (insert message-elide-ellipsis))
1753
1754 (defvar message-caesar-translation-table nil)
1755
1756 (defun message-caesar-region (b e &optional n)
1757   "Caesar rotation of region by N, default 13, for decrypting netnews."
1758   (interactive
1759    (list
1760     (min (point) (or (mark t) (point)))
1761     (max (point) (or (mark t) (point)))
1762     (when current-prefix-arg
1763       (prefix-numeric-value current-prefix-arg))))
1764
1765   (setq n (if (numberp n) (mod n 26) 13)) ;canonize N
1766   (unless (or (zerop n)                 ; no action needed for a rot of 0
1767               (= b e))                  ; no region to rotate
1768     ;; We build the table, if necessary.
1769     (when (or (not message-caesar-translation-table)
1770               (/= (aref message-caesar-translation-table ?a) (+ ?a n)))
1771       (setq message-caesar-translation-table
1772             (message-make-caesar-translation-table n)))
1773     (translate-region b e message-caesar-translation-table)))
1774
1775 (defun message-make-caesar-translation-table (n)
1776   "Create a rot table with offset N."
1777   (let ((i -1)
1778         (table (make-string 256 0)))
1779     (while (< (incf i) 256)
1780       (aset table i i))
1781     (concat
1782      (substring table 0 ?A)
1783      (substring table (+ ?A n) (+ ?A n (- 26 n)))
1784      (substring table ?A (+ ?A n))
1785      (substring table (+ ?A 26) ?a)
1786      (substring table (+ ?a n) (+ ?a n (- 26 n)))
1787      (substring table ?a (+ ?a n))
1788      (substring table (+ ?a 26) 255))))
1789
1790 (defun message-caesar-buffer-body (&optional rotnum)
1791   "Caesar rotates all letters in the current buffer by 13 places.
1792 Used to encode/decode possiblyun offensive messages (commonly in net.jokes).
1793 With prefix arg, specifies the number of places to rotate each letter forward.
1794 Mail and USENET news headers are not rotated."
1795   (interactive (if current-prefix-arg
1796                    (list (prefix-numeric-value current-prefix-arg))
1797                  (list nil)))
1798   (save-excursion
1799     (save-restriction
1800       (when (message-goto-body)
1801         (narrow-to-region (point) (point-max)))
1802       (message-caesar-region (point-min) (point-max) rotnum))))
1803
1804 (defun message-pipe-buffer-body (program)
1805   "Pipe the message body in the current buffer through PROGRAM."
1806   (save-excursion
1807     (save-restriction
1808       (when (message-goto-body)
1809         (narrow-to-region (point) (point-max)))
1810       (shell-command-on-region
1811        (point-min) (point-max) program nil t))))
1812
1813 (defun message-rename-buffer (&optional enter-string)
1814   "Rename the *message* buffer to \"*message* RECIPIENT\".
1815 If the function is run with a prefix, it will ask for a new buffer
1816 name, rather than giving an automatic name."
1817   (interactive "Pbuffer name: ")
1818   (save-excursion
1819     (save-restriction
1820       (goto-char (point-min))
1821       (narrow-to-region (point)
1822                         (search-forward mail-header-separator nil 'end))
1823       (let* ((mail-to (or
1824                        (if (message-news-p) (message-fetch-field "Newsgroups")
1825                          (message-fetch-field "To"))
1826                        ""))
1827              (mail-trimmed-to
1828               (if (string-match "," mail-to)
1829                   (concat (substring mail-to 0 (match-beginning 0)) ", ...")
1830                 mail-to))
1831              (name-default (concat "*message* " mail-trimmed-to))
1832              (name (if enter-string
1833                        (read-string "New buffer name: " name-default)
1834                      name-default)))
1835         (rename-buffer name t)))))
1836
1837 (defun message-fill-yanked-message (&optional justifyp)
1838   "Fill the paragraphs of a message yanked into this one.
1839 Numeric argument means justify as well."
1840   (interactive "P")
1841   (save-excursion
1842     (goto-char (point-min))
1843     (search-forward (concat "\n" mail-header-separator "\n") nil t)
1844     (let ((fill-prefix message-yank-prefix))
1845       (fill-individual-paragraphs (point) (point-max) justifyp))))
1846
1847 (defun message-indent-citation ()
1848   "Modify text just inserted from a message to be cited.
1849 The inserted text should be the region.
1850 When this function returns, the region is again around the modified text.
1851
1852 Normally, indent each nonblank line `message-indentation-spaces' spaces.
1853 However, if `message-yank-prefix' is non-nil, insert that prefix on each line."
1854   (let ((start (point)))
1855     ;; Remove unwanted headers.
1856     (when message-ignored-cited-headers
1857       (let (all-removed)
1858         (save-restriction
1859           (narrow-to-region
1860            (goto-char start)
1861            (if (search-forward "\n\n" nil t)
1862                (1- (point))
1863              (point)))
1864           (message-remove-header message-ignored-cited-headers t)
1865           (when (= (point-min) (point-max))
1866             (setq all-removed t))
1867           (goto-char (point-max)))
1868         (if all-removed
1869             (goto-char start)
1870           (forward-line 1))))
1871     ;; Delete blank lines at the start of the buffer.
1872     (while (and (point-min)
1873                 (eolp)
1874                 (not (eobp)))
1875       (message-delete-line))
1876     ;; Delete blank lines at the end of the buffer.
1877     (goto-char (point-max))
1878     (unless (eolp)
1879       (insert "\n"))
1880     (while (and (zerop (forward-line -1))
1881                 (looking-at "$"))
1882       (message-delete-line))
1883     ;; Do the indentation.
1884     (if (null message-yank-prefix)
1885         (indent-rigidly start (mark t) message-indentation-spaces)
1886       (save-excursion
1887         (goto-char start)
1888         (while (< (point) (mark t))
1889           (insert message-yank-prefix)
1890           (forward-line 1))))
1891     (goto-char start)))
1892
1893 (defun message-yank-original (&optional arg)
1894   "Insert the message being replied to, if any.
1895 Puts point before the text and mark after.
1896 Normally indents each nonblank line ARG spaces (default 3).  However,
1897 if `message-yank-prefix' is non-nil, insert that prefix on each line.
1898
1899 This function uses `message-cite-function' to do the actual citing.
1900
1901 Just \\[universal-argument] as argument means don't indent, insert no
1902 prefix, and don't delete any headers."
1903   (interactive "P")
1904   (let ((modified (buffer-modified-p)))
1905     (when (and message-reply-buffer
1906                message-cite-function)
1907       (delete-windows-on message-reply-buffer t)
1908       (insert-buffer message-reply-buffer)
1909       (funcall message-cite-function)
1910       (message-exchange-point-and-mark)
1911       (unless (bolp)
1912         (insert ?\n))
1913       (unless modified
1914         (setq message-checksum (message-checksum))))))
1915
1916 (defun message-yank-buffer (buffer)
1917   "Insert BUFFER into the current buffer and quote it."
1918   (interactive "bYank buffer: ")
1919   (let ((message-reply-buffer buffer))
1920     (save-window-excursion
1921       (message-yank-original))))
1922
1923 (defun message-buffers ()
1924   "Return a list of active message buffers."
1925   (let (buffers)
1926     (save-excursion
1927       (dolist (buffer (buffer-list t))
1928         (set-buffer buffer)
1929         (when (and (eq major-mode 'message-mode)
1930                    (null message-sent-message-via))
1931           (push (buffer-name buffer) buffers))))
1932     (nreverse buffers)))
1933
1934 (defun message-cite-original-without-signature ()
1935   "Cite function in the standard Message manner."
1936   (let ((start (point))
1937         (end (mark t))
1938         (functions
1939          (when message-indent-citation-function
1940            (if (listp message-indent-citation-function)
1941                message-indent-citation-function
1942              (list message-indent-citation-function)))))
1943     (mml-quote-region start end)
1944     ;; Allow undoing.
1945     (undo-boundary)
1946     (goto-char end)
1947     (when (re-search-backward message-signature-separator start t)
1948       ;; Also peel off any blank lines before the signature.
1949       (forward-line -1)
1950       (while (looking-at "^[ \t]*$")
1951         (forward-line -1))
1952       (forward-line 1)
1953       (delete-region (point) end))
1954     (goto-char start)
1955     (while functions
1956       (funcall (pop functions)))
1957     (when message-citation-line-function
1958       (unless (bolp)
1959         (insert "\n"))
1960       (funcall message-citation-line-function))))
1961
1962 (defvar mail-citation-hook)             ;Compiler directive
1963 (defun message-cite-original ()
1964   "Cite function in the standard Message manner."
1965   (if (and (boundp 'mail-citation-hook)
1966            mail-citation-hook)
1967       (run-hooks 'mail-citation-hook)
1968     (let ((start (point))
1969           (end (mark t))
1970           (functions
1971            (when message-indent-citation-function
1972              (if (listp message-indent-citation-function)
1973                  message-indent-citation-function
1974                (list message-indent-citation-function)))))
1975       (mml-quote-region start end)
1976       (goto-char start)
1977       (while functions
1978         (funcall (pop functions)))
1979       (when message-citation-line-function
1980         (unless (bolp)
1981           (insert "\n"))
1982         (funcall message-citation-line-function)))))
1983
1984 (defun message-insert-citation-line ()
1985   "Function that inserts a simple citation line."
1986   (when message-reply-headers
1987     (insert (mail-header-from message-reply-headers) " writes:\n\n")))
1988
1989 (defun message-position-on-field (header &rest afters)
1990   (let ((case-fold-search t))
1991     (save-restriction
1992       (narrow-to-region
1993        (goto-char (point-min))
1994        (progn
1995          (re-search-forward
1996           (concat "^" (regexp-quote mail-header-separator) "$"))
1997          (match-beginning 0)))
1998       (goto-char (point-min))
1999       (if (re-search-forward (concat "^" (regexp-quote header) ":") nil t)
2000           (progn
2001             (re-search-forward "^[^ \t]" nil 'move)
2002             (beginning-of-line)
2003             (skip-chars-backward "\n")
2004             t)
2005         (while (and afters
2006                     (not (re-search-forward
2007                           (concat "^" (regexp-quote (car afters)) ":")
2008                           nil t)))
2009           (pop afters))
2010         (when afters
2011           (re-search-forward "^[^ \t]" nil 'move)
2012           (beginning-of-line))
2013         (insert header ": \n")
2014         (forward-char -1)
2015         nil))))
2016
2017 (defun message-remove-signature ()
2018   "Remove the signature from the text between point and mark.
2019 The text will also be indented the normal way."
2020   (save-excursion
2021     (let ((start (point))
2022           mark)
2023       (if (not (re-search-forward message-signature-separator (mark t) t))
2024           ;; No signature here, so we just indent the cited text.
2025           (message-indent-citation)
2026         ;; Find the last non-empty line.
2027         (forward-line -1)
2028         (while (looking-at "[ \t]*$")
2029           (forward-line -1))
2030         (forward-line 1)
2031         (setq mark (set-marker (make-marker) (point)))
2032         (goto-char start)
2033         (message-indent-citation)
2034         ;; Enable undoing the deletion.
2035         (undo-boundary)
2036         (delete-region mark (mark t))
2037         (set-marker mark nil)))))
2038
2039 \f
2040
2041 ;;;
2042 ;;; Sending messages
2043 ;;;
2044
2045 (defun message-send-and-exit (&optional arg)
2046   "Send message like `message-send', then, if no errors, exit from mail buffer."
2047   (interactive "P")
2048   (let ((buf (current-buffer))
2049         (actions message-exit-actions))
2050     (when (and (message-send arg)
2051                (buffer-name buf))
2052       (if message-kill-buffer-on-exit
2053           (kill-buffer buf)
2054         (bury-buffer buf)
2055         (when (eq buf (current-buffer))
2056           (message-bury buf)))
2057       (message-do-actions actions)
2058       t)))
2059
2060 (defun message-dont-send ()
2061   "Don't send the message you have been editing."
2062   (interactive)
2063   (set-buffer-modified-p t)
2064   (save-buffer)
2065   (let ((actions message-postpone-actions))
2066     (message-bury (current-buffer))
2067     (message-do-actions actions)))
2068
2069 (defun message-kill-buffer ()
2070   "Kill the current buffer."
2071   (interactive)
2072   (when (or (not (buffer-modified-p))
2073             (yes-or-no-p "Message modified; kill anyway? "))
2074     (let ((actions message-kill-actions))
2075       (setq buffer-file-name nil)
2076       (kill-buffer (current-buffer))
2077       (message-do-actions actions))))
2078
2079 (defun message-bury (buffer)
2080   "Bury this mail buffer."
2081   (let ((newbuf (other-buffer buffer)))
2082     (bury-buffer buffer)
2083     (if (and (fboundp 'frame-parameters)
2084              (cdr (assq 'dedicated (frame-parameters)))
2085              (not (null (delq (selected-frame) (visible-frame-list)))))
2086         (delete-frame (selected-frame))
2087       (switch-to-buffer newbuf))))
2088
2089 (defun message-send (&optional arg)
2090   "Send the message in the current buffer.
2091 If `message-interactive' is non-nil, wait for success indication or
2092 error messages, and inform user.
2093 Otherwise any failure is reported in a message back to the user from
2094 the mailer.
2095 The usage of ARG is defined by the instance that called Message.
2096 It should typically alter the sending method in some way or other."
2097   (interactive "P")
2098   ;; Make it possible to undo the coming changes.
2099   (undo-boundary)
2100   (let ((inhibit-read-only t))
2101     (put-text-property (point-min) (point-max) 'read-only nil))
2102   (message-fix-before-sending)
2103   (run-hooks 'message-send-hook)
2104   (message "Sending...")
2105   (let ((alist message-send-method-alist)
2106         (success t)
2107         elem sent)
2108     (while (and success
2109                 (setq elem (pop alist)))
2110       (when (or (not (funcall (cadr elem)))
2111                 (and (or (not (memq (car elem)
2112                                     message-sent-message-via))
2113                          (y-or-n-p
2114                           (format
2115                            "Already sent message via %s; resend? "
2116                            (car elem))))
2117                      (setq success (funcall (caddr elem) arg))))
2118         (setq sent t)))
2119     (unless (or sent (not success))
2120       (error "No methods specified to send by"))
2121     (when (and success sent)
2122       (message-do-fcc)
2123       (save-excursion
2124         (run-hooks 'message-sent-hook))
2125       (message "Sending...done")
2126       ;; Mark the buffer as unmodified and delete auto-save.
2127       (set-buffer-modified-p nil)
2128       (delete-auto-save-file-if-necessary t)
2129       (message-disassociate-draft)
2130       ;; Delete other mail buffers and stuff.
2131       (message-do-send-housekeeping)
2132       (message-do-actions message-send-actions)
2133       ;; Return success.
2134       t)))
2135
2136 (defun message-send-via-mail (arg)
2137   "Send the current message via mail."
2138   (message-send-mail arg))
2139
2140 (defun message-send-via-news (arg)
2141   "Send the current message via news."
2142   (funcall message-send-news-function arg))
2143
2144 (defmacro message-check (type &rest forms)
2145   "Eval FORMS if TYPE is to be checked."
2146   `(or (message-check-element ,type)
2147        (save-excursion
2148          ,@forms)))
2149
2150 (put 'message-check 'lisp-indent-function 1)
2151 (put 'message-check 'edebug-form-spec '(form body))
2152
2153 (defun message-fix-before-sending ()
2154   "Do various things to make the message nice before sending it."
2155   ;; Make sure there's a newline at the end of the message.
2156   (goto-char (point-max))
2157   (unless (bolp)
2158     (insert "\n"))
2159   ;; Delete all invisible text.
2160   (message-check 'invisible-text
2161     (when (text-property-any (point-min) (point-max) 'invisible t)
2162       (put-text-property (point-min) (point-max) 'invisible nil)
2163       (unless (yes-or-no-p
2164                "Invisible text found and made visible; continue posting? ")
2165         (error "Invisible text found and made visible")))))
2166
2167 (defun message-add-action (action &rest types)
2168   "Add ACTION to be performed when doing an exit of type TYPES."
2169   (let (var)
2170     (while types
2171       (set (setq var (intern (format "message-%s-actions" (pop types))))
2172            (nconc (symbol-value var) (list action))))))
2173
2174 (defun message-do-actions (actions)
2175   "Perform all actions in ACTIONS."
2176   ;; Now perform actions on successful sending.
2177   (while actions
2178     (ignore-errors
2179       (cond
2180        ;; A simple function.
2181        ((message-functionp (car actions))
2182         (funcall (car actions)))
2183        ;; Something to be evaled.
2184        (t
2185         (eval (car actions)))))
2186     (pop actions)))
2187
2188 (defun message-send-mail-partially ()
2189   "Sendmail as message/partial."
2190   (let ((p (goto-char (point-min)))
2191         (tembuf (message-generate-new-buffer-clone-locals " message temp"))
2192         (curbuf (current-buffer))
2193         (id (message-make-message-id)) (n 1)
2194         plist total  header required-mail-headers)
2195     (while (not (eobp))
2196       (if (< (point-max) (+ p message-send-mail-partially-limit))
2197           (goto-char (point-max))
2198         (goto-char (+ p message-send-mail-partially-limit))
2199         (beginning-of-line)
2200         (if (<= (point) p) (forward-line 1))) ;; In case of bad message.
2201       (push p plist)
2202       (setq p (point)))
2203     (setq total (length plist))
2204     (push (point-max) plist)
2205     (setq plist (nreverse plist))
2206     (unwind-protect
2207         (save-excursion
2208           (setq p (pop plist))
2209           (while plist
2210             (set-buffer curbuf)
2211             (copy-to-buffer tembuf p (car plist))
2212             (set-buffer tembuf)
2213             (goto-char (point-min))
2214             (if header
2215                 (progn
2216                   (goto-char (point-min))
2217                   (narrow-to-region (point) (point))
2218                   (insert header))
2219               (message-goto-eoh)
2220               (setq header (buffer-substring (point-min) (point)))
2221               (goto-char (point-min))
2222               (narrow-to-region (point) (point))
2223               (insert header)
2224               (message-remove-header "Mime-Version")
2225               (message-remove-header "Content-Type")
2226               (message-remove-header "Content-Transfer-Encoding")
2227               (message-remove-header "Message-ID")
2228               (message-remove-header "Lines")
2229               (goto-char (point-max))
2230               (insert "Mime-Version: 1.0\n")
2231               (setq header (buffer-substring (point-min) (point-max))))
2232             (goto-char (point-max))
2233             (insert (format "Content-Type: message/partial; id=\"%s\"; number=%d; total=%d\n"
2234                             id n total))
2235             (let ((mail-header-separator ""))
2236               (when (memq 'Message-ID message-required-mail-headers)
2237                 (insert "Message-ID: " (message-make-message-id) "\n"))
2238               (when (memq 'Lines message-required-mail-headers)
2239                 (let ((mail-header-separator ""))
2240                   (insert "Lines: " (message-make-lines) "\n")))
2241               (message-goto-subject)
2242               (end-of-line)
2243               (insert (format " (%d/%d)" n total))
2244               (goto-char (point-max))
2245               (insert "\n")
2246               (widen)
2247               (mm-with-unibyte-current-buffer
2248                 (funcall message-send-mail-function)))
2249             (setq n (+ n 1))
2250             (setq p (pop plist))
2251             (erase-buffer)))
2252       (kill-buffer tembuf))))
2253
2254 (defun message-send-mail (&optional arg)
2255   (require 'mail-utils)
2256   (let* ((tembuf (message-generate-new-buffer-clone-locals " message temp"))
2257          (case-fold-search nil)
2258          (news (message-news-p))
2259          (mailbuf (current-buffer))
2260          (message-this-is-mail t)
2261          (message-posting-charset
2262           (if (fboundp 'gnus-setup-posting-charset)
2263               (gnus-setup-posting-charset nil)
2264             message-posting-charset)))
2265     (save-restriction
2266       (message-narrow-to-headers)
2267       ;; Insert some headers.
2268       (let ((message-deletable-headers
2269              (if news nil message-deletable-headers)))
2270         (message-generate-headers message-required-mail-headers))
2271       ;; Let the user do all of the above.
2272       (run-hooks 'message-header-hook))
2273     (unwind-protect
2274         (save-excursion
2275           (set-buffer tembuf)
2276           (erase-buffer)
2277           ;; Avoid copying text props.
2278           (insert (format
2279                    "%s" (save-excursion
2280                           (set-buffer mailbuf)
2281                           (buffer-string))))
2282           ;; Remove some headers.
2283           (message-encode-message-body)
2284           (save-restriction
2285             (message-narrow-to-headers)
2286             ;; We (re)generate the Lines header.
2287             (when (memq 'Lines message-required-mail-headers)
2288               (message-generate-headers '(Lines)))
2289             ;; Remove some headers.
2290             (message-remove-header message-ignored-mail-headers t)
2291             (let ((mail-parse-charset message-default-charset))
2292               (mail-encode-encoded-word-buffer)))
2293           (goto-char (point-max))
2294           ;; require one newline at the end.
2295           (or (= (preceding-char) ?\n)
2296               (insert ?\n))
2297           (when 
2298               (save-restriction
2299                 (message-narrow-to-headers)
2300                 (and news
2301                      (or (message-fetch-field "cc")
2302                          (message-fetch-field "to"))
2303                      (string= "text/plain"
2304                               (car
2305                                (mail-header-parse-content-type
2306                                 (message-fetch-field "content-type"))))))
2307             (message-insert-courtesy-copy))
2308           (if (or (not message-send-mail-partially-limit)
2309                   (< (point-max) message-send-mail-partially-limit)
2310                   (not (y-or-n-p "The message size is too large, should it be sent partially?")))
2311               (mm-with-unibyte-current-buffer
2312                 (funcall message-send-mail-function))
2313             (message-send-mail-partially)))
2314       (kill-buffer tembuf))
2315     (set-buffer mailbuf)
2316     (push 'mail message-sent-message-via)))
2317
2318 (defun message-send-mail-with-sendmail ()
2319   "Send off the prepared buffer with sendmail."
2320   (let ((errbuf (if message-interactive
2321                     (message-generate-new-buffer-clone-locals
2322                      " sendmail errors")
2323                   0))
2324         resend-to-addresses delimline)
2325     (let ((case-fold-search t))
2326       (save-restriction
2327         (message-narrow-to-headers)
2328         (setq resend-to-addresses (message-fetch-field "resent-to")))
2329       ;; Change header-delimiter to be what sendmail expects.
2330       (goto-char (point-min))
2331       (re-search-forward
2332        (concat "^" (regexp-quote mail-header-separator) "\n"))
2333       (replace-match "\n")
2334       (backward-char 1)
2335       (setq delimline (point-marker))
2336       (run-hooks 'message-send-mail-hook)
2337       ;; Insert an extra newline if we need it to work around
2338       ;; Sun's bug that swallows newlines.
2339       (goto-char (1+ delimline))
2340       (when (eval message-mailer-swallows-blank-line)
2341         (newline))
2342       (when message-interactive
2343         (save-excursion
2344           (set-buffer errbuf)
2345           (erase-buffer))))
2346     (let ((default-directory "/")
2347           (coding-system-for-write message-send-coding-system))
2348       (apply 'call-process-region
2349              (append (list (point-min) (point-max)
2350                            (if (boundp 'sendmail-program)
2351                                sendmail-program
2352                              "/usr/lib/sendmail")
2353                            nil errbuf nil "-oi")
2354                      ;; Always specify who from,
2355                      ;; since some systems have broken sendmails.
2356                      ;; But some systems are more broken with -f, so
2357                      ;; we'll let users override this.
2358                      (if (null message-sendmail-f-is-evil)
2359                          (list "-f" (message-make-address)))
2360                      ;; These mean "report errors by mail"
2361                      ;; and "deliver in background".
2362                      (if (null message-interactive) '("-oem" "-odb"))
2363                      ;; Get the addresses from the message
2364                      ;; unless this is a resend.
2365                      ;; We must not do that for a resend
2366                      ;; because we would find the original addresses.
2367                      ;; For a resend, include the specific addresses.
2368                      (if resend-to-addresses
2369                          (list resend-to-addresses)
2370                        '("-t")))))
2371     (when message-interactive
2372       (save-excursion
2373         (set-buffer errbuf)
2374         (goto-char (point-min))
2375         (while (re-search-forward "\n\n* *" nil t)
2376           (replace-match "; "))
2377         (if (not (zerop (buffer-size)))
2378             (error "Sending...failed to %s"
2379                    (buffer-substring (point-min) (point-max)))))
2380       (when (bufferp errbuf)
2381         (kill-buffer errbuf)))))
2382
2383 (defun message-send-mail-with-qmail ()
2384   "Pass the prepared message buffer to qmail-inject.
2385 Refer to the documentation for the variable `message-send-mail-function'
2386 to find out how to use this."
2387   ;; replace the header delimiter with a blank line
2388   (goto-char (point-min))
2389   (re-search-forward
2390    (concat "^" (regexp-quote mail-header-separator) "\n"))
2391   (replace-match "\n")
2392   (run-hooks 'message-send-mail-hook)
2393   ;; send the message
2394   (case
2395       (let ((coding-system-for-write message-send-coding-system))
2396         (apply
2397          'call-process-region 1 (point-max) message-qmail-inject-program
2398          nil nil nil
2399          ;; qmail-inject's default behaviour is to look for addresses on the
2400          ;; command line; if there're none, it scans the headers.
2401          ;; yes, it does The Right Thing w.r.t. Resent-To and it's kin.
2402          ;;
2403          ;; in general, ALL of qmail-inject's defaults are perfect for simply
2404          ;; reading a formatted (i. e., at least a To: or Resent-To header)
2405          ;; message from stdin.
2406          ;;
2407          ;; qmail also has the advantage of not having been raped by
2408          ;; various vendors, so we don't have to allow for that, either --
2409          ;; compare this with message-send-mail-with-sendmail and weep
2410          ;; for sendmail's lost innocence.
2411          ;;
2412          ;; all this is way cool coz it lets us keep the arguments entirely
2413          ;; free for -inject-arguments -- a big win for the user and for us
2414          ;; since we don't have to play that double-guessing game and the user
2415          ;; gets full control (no gestapo'ish -f's, for instance).  --sj
2416          message-qmail-inject-args))
2417     ;; qmail-inject doesn't say anything on it's stdout/stderr,
2418     ;; we have to look at the retval instead
2419     (0 nil)
2420     (1   (error "qmail-inject reported permanent failure"))
2421     (111 (error "qmail-inject reported transient failure"))
2422     ;; should never happen
2423     (t   (error "qmail-inject reported unknown failure"))))
2424
2425 (defun message-send-mail-with-mh ()
2426   "Send the prepared message buffer with mh."
2427   (let ((mh-previous-window-config nil)
2428         (name (mh-new-draft-name)))
2429     (setq buffer-file-name name)
2430     ;; MH wants to generate these headers itself.
2431     (when message-mh-deletable-headers
2432       (let ((headers message-mh-deletable-headers))
2433         (while headers
2434           (goto-char (point-min))
2435           (and (re-search-forward
2436                 (concat "^" (symbol-name (car headers)) ": *") nil t)
2437                (message-delete-line))
2438           (pop headers))))
2439     (run-hooks 'message-send-mail-hook)
2440     ;; Pass it on to mh.
2441     (mh-send-letter)))
2442
2443 (defun message-send-news (&optional arg)
2444   (let* ((tembuf (message-generate-new-buffer-clone-locals " *message temp*"))
2445          (case-fold-search nil)
2446          (method (if (message-functionp message-post-method)
2447                      (funcall message-post-method arg)
2448                    message-post-method))
2449          (group-name-charset (gnus-group-name-charset method ""))
2450          (rfc2047-header-encoding-alist
2451           (if group-name-charset
2452               (cons (cons "Newsgroups" group-name-charset)
2453                     rfc2047-header-encoding-alist)
2454             rfc2047-header-encoding-alist))
2455          (messbuf (current-buffer))
2456          (message-syntax-checks
2457           (if arg
2458               (cons '(existing-newsgroups . disabled)
2459                     message-syntax-checks)
2460             message-syntax-checks))
2461          (message-this-is-news t)
2462          (message-posting-charset (gnus-setup-posting-charset 
2463                                    (save-restriction
2464                                      (message-narrow-to-headers-or-head)
2465                                      (message-fetch-field "Newsgroups"))))
2466          result)
2467     (if (not (message-check-news-body-syntax))
2468         nil
2469       (save-restriction
2470         (message-narrow-to-headers)
2471         ;; Insert some headers.
2472         (message-generate-headers message-required-news-headers)
2473         ;; Let the user do all of the above.
2474         (run-hooks 'message-header-hook))
2475       (if group-name-charset
2476           (setq message-syntax-checks
2477               (cons '(valid-newsgroups . disabled)
2478                     message-syntax-checks)))
2479       (message-cleanup-headers)
2480       (if (not (message-check-news-syntax))
2481           nil
2482         (unwind-protect
2483             (save-excursion
2484               (set-buffer tembuf)
2485               (buffer-disable-undo)
2486               (erase-buffer)
2487               ;; Avoid copying text props.
2488               (insert (format
2489                        "%s" (save-excursion
2490                               (set-buffer messbuf)
2491                               (buffer-string))))
2492               (message-encode-message-body)
2493               ;; Remove some headers.
2494               (save-restriction
2495                 (message-narrow-to-headers)
2496                 ;; We (re)generate the Lines header.
2497                 (when (memq 'Lines message-required-mail-headers)
2498                   (message-generate-headers '(Lines)))
2499                 ;; Remove some headers.
2500                 (message-remove-header message-ignored-news-headers t)
2501                 (let ((mail-parse-charset message-default-charset))
2502                   (mail-encode-encoded-word-buffer)))
2503               (goto-char (point-max))
2504               ;; require one newline at the end.
2505               (or (= (preceding-char) ?\n)
2506                   (insert ?\n))
2507               (let ((case-fold-search t))
2508                 ;; Remove the delimiter.
2509                 (goto-char (point-min))
2510                 (re-search-forward
2511                  (concat "^" (regexp-quote mail-header-separator) "\n"))
2512                 (replace-match "\n")
2513                 (backward-char 1))
2514               (run-hooks 'message-send-news-hook)
2515               (gnus-open-server method)
2516               (setq result (let ((mail-header-separator ""))
2517                              (gnus-request-post method))))
2518           (kill-buffer tembuf))
2519         (set-buffer messbuf)
2520         (if result
2521             (push 'news message-sent-message-via)
2522           (message "Couldn't send message via news: %s"
2523                    (nnheader-get-report (car method)))
2524           nil)))))
2525
2526 ;;;
2527 ;;; Header generation & syntax checking.
2528 ;;;
2529
2530 (defun message-check-element (type)
2531   "Returns non-nil if this type is not to be checked."
2532   (if (eq message-syntax-checks 'dont-check-for-anything-just-trust-me)
2533       t
2534     (let ((able (assq type message-syntax-checks)))
2535       (and (consp able)
2536            (eq (cdr able) 'disabled)))))
2537
2538 (defun message-check-news-syntax ()
2539   "Check the syntax of the message."
2540   (save-excursion
2541     (save-restriction
2542       (widen)
2543       ;; We narrow to the headers and check them first.
2544       (save-excursion
2545         (save-restriction
2546           (message-narrow-to-headers)
2547           (message-check-news-header-syntax))))))
2548
2549 (defun message-check-news-header-syntax ()
2550   (and
2551    ;; Check Newsgroups header.
2552    (message-check 'newsgroups
2553      (let ((group (message-fetch-field "newsgroups")))
2554        (or
2555         (and group
2556              (not (string-match "\\`[ \t]*\\'" group)))
2557         (ignore
2558          (message
2559           "The newsgroups field is empty or missing.  Posting is denied.")))))
2560    ;; Check the Subject header.
2561    (message-check 'subject
2562      (let* ((case-fold-search t)
2563             (subject (message-fetch-field "subject")))
2564        (or
2565         (and subject
2566              (not (string-match "\\`[ \t]*\\'" subject)))
2567         (ignore
2568          (message
2569           "The subject field is empty or missing.  Posting is denied.")))))
2570    ;; Check for commands in Subject.
2571    (message-check 'subject-cmsg
2572      (if (string-match "^cmsg " (message-fetch-field "subject"))
2573          (y-or-n-p
2574           "The control code \"cmsg\" is in the subject.  Really post? ")
2575        t))
2576    ;; Check for multiple identical headers.
2577    (message-check 'multiple-headers
2578      (let (found)
2579        (while (and (not found)
2580                    (re-search-forward "^[^ \t:]+: " nil t))
2581          (save-excursion
2582            (or (re-search-forward
2583                 (concat "^"
2584                         (regexp-quote
2585                          (setq found
2586                                (buffer-substring
2587                                 (match-beginning 0) (- (match-end 0) 2))))
2588                         ":")
2589                 nil t)
2590                (setq found nil))))
2591        (if found
2592            (y-or-n-p (format "Multiple %s headers.  Really post? " found))
2593          t)))
2594    ;; Check for Version and Sendsys.
2595    (message-check 'sendsys
2596      (if (re-search-forward "^Sendsys:\\|^Version:" nil t)
2597          (y-or-n-p
2598           (format "The article contains a %s command.  Really post? "
2599                   (buffer-substring (match-beginning 0)
2600                                     (1- (match-end 0)))))
2601        t))
2602    ;; See whether we can shorten Followup-To.
2603    (message-check 'shorten-followup-to
2604      (let ((newsgroups (message-fetch-field "newsgroups"))
2605            (followup-to (message-fetch-field "followup-to"))
2606            to)
2607        (when (and newsgroups
2608                   (string-match "," newsgroups)
2609                   (not followup-to)
2610                   (not
2611                    (zerop
2612                     (length
2613                      (setq to (completing-read
2614                                "Followups to: (default all groups) "
2615                                (mapcar (lambda (g) (list g))
2616                                        (cons "poster"
2617                                              (message-tokenize-header
2618                                               newsgroups)))))))))
2619          (goto-char (point-min))
2620          (insert "Followup-To: " to "\n"))
2621        t))
2622    ;; Check "Shoot me".
2623    (message-check 'shoot
2624      (if (re-search-forward
2625           "Message-ID.*.i-did-not-set--mail-host-address--so-shoot-me" nil t)
2626          (y-or-n-p "You appear to have a misconfigured system.  Really post? ")
2627        t))
2628    ;; Check for Approved.
2629    (message-check 'approved
2630      (if (re-search-forward "^Approved:" nil t)
2631          (y-or-n-p "The article contains an Approved header.  Really post? ")
2632        t))
2633    ;; Check the Message-ID header.
2634    (message-check 'message-id
2635      (let* ((case-fold-search t)
2636             (message-id (message-fetch-field "message-id" t)))
2637        (or (not message-id)
2638            ;; Is there an @ in the ID?
2639            (and (string-match "@" message-id)
2640                 ;; Is there a dot in the ID?
2641                 (string-match "@[^.]*\\." message-id)
2642                 ;; Does the ID end with a dot?
2643                 (not (string-match "\\.>" message-id)))
2644            (y-or-n-p
2645             (format "The Message-ID looks strange: \"%s\".  Really post? "
2646                     message-id)))))
2647    ;; Check the Newsgroups & Followup-To headers.
2648    (message-check 'existing-newsgroups
2649      (let* ((case-fold-search t)
2650             (newsgroups (message-fetch-field "newsgroups"))
2651             (followup-to (message-fetch-field "followup-to"))
2652             (groups (message-tokenize-header
2653                      (if followup-to
2654                          (concat newsgroups "," followup-to)
2655                        newsgroups)))
2656             (hashtb (and (boundp 'gnus-active-hashtb)
2657                          gnus-active-hashtb))
2658             errors)
2659        (if (or (not hashtb)
2660                (not (boundp 'gnus-read-active-file))
2661                (not gnus-read-active-file)
2662                (eq gnus-read-active-file 'some))
2663            t
2664          (while groups
2665            (when (and (not (boundp (intern (car groups) hashtb)))
2666                       (not (equal (car groups) "poster")))
2667              (push (car groups) errors))
2668            (pop groups))
2669          (if (not errors)
2670              t
2671            (y-or-n-p
2672             (format
2673              "Really post to %s unknown group%s: %s "
2674              (if (= (length errors) 1) "this" "these")
2675              (if (= (length errors) 1) "" "s")
2676              (mapconcat 'identity errors ", ")))))))
2677    ;; Check the Newsgroups & Followup-To headers for syntax errors.
2678    (message-check 'valid-newsgroups
2679      (let ((case-fold-search t)
2680            (headers '("Newsgroups" "Followup-To"))
2681            header error)
2682        (while (and headers (not error))
2683          (when (setq header (mail-fetch-field (car headers)))
2684            (if (or
2685                 (not
2686                  (string-match
2687                   "\\`\\([-+_&.a-zA-Z0-9]+\\)?\\(,[-+_&.a-zA-Z0-9]+\\)*\\'"
2688                   header))
2689                 (memq
2690                  nil (mapcar
2691                       (lambda (g)
2692                         (not (string-match "\\.\\'\\|\\.\\." g)))
2693                       (message-tokenize-header header ","))))
2694                (setq error t)))
2695          (unless error
2696            (pop headers)))
2697        (if (not error)
2698            t
2699          (y-or-n-p
2700           (format "The %s header looks odd: \"%s\".  Really post? "
2701                   (car headers) header)))))
2702    (message-check 'repeated-newsgroups
2703      (let ((case-fold-search t)
2704            (headers '("Newsgroups" "Followup-To"))
2705            header error groups group)
2706        (while (and headers
2707                    (not error))
2708          (when (setq header (mail-fetch-field (pop headers)))
2709            (setq groups (message-tokenize-header header ","))
2710            (while (setq group (pop groups))
2711              (when (member group groups)
2712                (setq error group
2713                      groups nil)))))
2714        (if (not error)
2715            t
2716          (y-or-n-p
2717           (format "Group %s is repeated in headers.  Really post? " error)))))
2718    ;; Check the From header.
2719    (message-check 'from
2720      (let* ((case-fold-search t)
2721             (from (message-fetch-field "from"))
2722             ad)
2723        (cond
2724         ((not from)
2725          (message "There is no From line.  Posting is denied.")
2726          nil)
2727         ((or (not (string-match
2728                    "@[^\\.]*\\."
2729                    (setq ad (nth 1 (mail-extract-address-components
2730                                     from))))) ;larsi@ifi
2731              (string-match "\\.\\." ad) ;larsi@ifi..uio
2732              (string-match "@\\." ad)   ;larsi@.ifi.uio
2733              (string-match "\\.$" ad)   ;larsi@ifi.uio.
2734              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
2735              (string-match "(.*).*(.*)" from)) ;(lars) (lars)
2736          (message
2737           "Denied posting -- the From looks strange: \"%s\"." from)
2738          nil)
2739         (t t))))))
2740
2741 (defun message-check-news-body-syntax ()
2742   (and
2743    ;; Check for long lines.
2744    (message-check 'long-lines
2745      (goto-char (point-min))
2746      (re-search-forward
2747       (concat "^" (regexp-quote mail-header-separator) "$"))
2748      (while (and
2749              (progn
2750                (end-of-line)
2751                (< (current-column) 80))
2752              (zerop (forward-line 1))))
2753      (or (bolp)
2754          (eobp)
2755          (y-or-n-p
2756           "You have lines longer than 79 characters.  Really post? ")))
2757    ;; Check whether the article is empty.
2758    (message-check 'empty
2759      (goto-char (point-min))
2760      (re-search-forward
2761       (concat "^" (regexp-quote mail-header-separator) "$"))
2762      (forward-line 1)
2763      (let ((b (point)))
2764        (goto-char (point-max))
2765        (re-search-backward message-signature-separator nil t)
2766        (beginning-of-line)
2767        (or (re-search-backward "[^ \n\t]" b t)
2768            (y-or-n-p "Empty article.  Really post? "))))
2769    ;; Check for control characters.
2770    (message-check 'control-chars
2771      (if (re-search-forward "[\000-\007\013\015-\032\034-\037\200-\237]" nil t)
2772          (y-or-n-p
2773           "The article contains control characters.  Really post? ")
2774        t))
2775    ;; Check excessive size.
2776    (message-check 'size
2777      (if (> (buffer-size) 60000)
2778          (y-or-n-p
2779           (format "The article is %d octets long.  Really post? "
2780                   (buffer-size)))
2781        t))
2782    ;; Check whether any new text has been added.
2783    (message-check 'new-text
2784      (or
2785       (not message-checksum)
2786       (not (eq (message-checksum) message-checksum))
2787       (y-or-n-p
2788        "It looks like no new text has been added.  Really post? ")))
2789    ;; Check the length of the signature.
2790    (message-check 'signature
2791      (goto-char (point-max))
2792      (if (> (count-lines (point) (point-max)) 5)
2793          (y-or-n-p
2794           (format
2795            "Your .sig is %d lines; it should be max 4.  Really post? "
2796            (1- (count-lines (point) (point-max)))))
2797        t))
2798    ;; Ensure that text follows last quoted portion.
2799    (message-check 'quoting-style
2800      (goto-char (point-max))
2801      (let ((no-problem t))
2802        (when (search-backward-regexp "^>[^\n]*\n>" nil t)
2803          (setq no-problem nil)
2804          (while (not (eobp))
2805            (when (and (not (eolp)) (looking-at "[^> \t]"))
2806              (setq no-problem t))
2807            (forward-line)))
2808        (if no-problem
2809            t
2810          (y-or-n-p "Your text should follow quoted text.  Really post? "))))))
2811
2812 (defun message-checksum ()
2813   "Return a \"checksum\" for the current buffer."
2814   (let ((sum 0))
2815     (save-excursion
2816       (goto-char (point-min))
2817       (re-search-forward
2818        (concat "^" (regexp-quote mail-header-separator) "$"))
2819       (while (not (eobp))
2820         (when (not (looking-at "[ \t\n]"))
2821           (setq sum (logxor (ash sum 1) (if (natnump sum) 0 1)
2822                             (char-after))))
2823         (forward-char 1)))
2824     sum))
2825
2826 (defun message-do-fcc ()
2827   "Process Fcc headers in the current buffer."
2828   (let ((case-fold-search t)
2829         (buf (current-buffer))
2830         list file)
2831     (save-excursion
2832       (set-buffer (get-buffer-create " *message temp*"))
2833       (erase-buffer)
2834       (insert-buffer-substring buf)
2835       (save-restriction
2836         (message-narrow-to-headers)
2837         (while (setq file (message-fetch-field "fcc"))
2838           (push file list)
2839           (message-remove-header "fcc" nil t)))
2840       (message-encode-message-body)
2841       (save-restriction
2842         (message-narrow-to-headers)
2843         (let ((mail-parse-charset message-default-charset)
2844               (rfc2047-header-encoding-alist
2845                (cons '("Newsgroups" . default)
2846                      rfc2047-header-encoding-alist)))
2847           (mail-encode-encoded-word-buffer)))
2848       (goto-char (point-min))
2849       (when (re-search-forward
2850              (concat "^" (regexp-quote mail-header-separator) "$")
2851              nil t)
2852         (replace-match "" t t ))
2853       ;; Process FCC operations.
2854       (while list
2855         (setq file (pop list))
2856         (if (string-match "^[ \t]*|[ \t]*\\(.*\\)[ \t]*$" file)
2857             ;; Pipe the article to the program in question.
2858             (call-process-region (point-min) (point-max) shell-file-name
2859                                  nil nil nil shell-command-switch
2860                                  (match-string 1 file))
2861           ;; Save the article.
2862           (setq file (expand-file-name file))
2863           (unless (file-exists-p (file-name-directory file))
2864             (make-directory (file-name-directory file) t))
2865           (if (and message-fcc-handler-function
2866                    (not (eq message-fcc-handler-function 'rmail-output)))
2867               (funcall message-fcc-handler-function file)
2868             (if (and (file-readable-p file) (mail-file-babyl-p file))
2869                 (rmail-output file 1 nil t)
2870               (let ((mail-use-rfc822 t))
2871                 (rmail-output file 1 t t))))))
2872       (kill-buffer (current-buffer)))))
2873
2874 (defun message-output (filename)
2875   "Append this article to Unix/babyl mail file.."
2876   (if (and (file-readable-p filename)
2877            (mail-file-babyl-p filename))
2878       (gnus-output-to-rmail filename t)
2879     (gnus-output-to-mail filename t)))
2880
2881 (defun message-cleanup-headers ()
2882   "Do various automatic cleanups of the headers."
2883   ;; Remove empty lines in the header.
2884   (save-restriction
2885     (message-narrow-to-headers)
2886     ;; Remove blank lines.
2887     (while (re-search-forward "^[ \t]*\n" nil t)
2888       (replace-match "" t t))
2889
2890     ;; Correct Newsgroups and Followup-To headers:  Change sequence of
2891     ;; spaces to comma and eliminate spaces around commas.  Eliminate
2892     ;; embedded line breaks.
2893     (goto-char (point-min))
2894     (while (re-search-forward "^\\(Newsgroups\\|Followup-To\\): +" nil t)
2895       (save-restriction
2896         (narrow-to-region
2897          (point)
2898          (if (re-search-forward "^[^ \t]" nil t)
2899              (match-beginning 0)
2900            (forward-line 1)
2901            (point)))
2902         (goto-char (point-min))
2903         (while (re-search-forward "\n[ \t]+" nil t)
2904           (replace-match " " t t))      ;No line breaks (too confusing)
2905         (goto-char (point-min))
2906         (while (re-search-forward "[ \t\n]*,[ \t\n]*\\|[ \t]+" nil t)
2907           (replace-match "," t t))
2908         (goto-char (point-min))
2909         ;; Remove trailing commas.
2910         (when (re-search-forward ",+$" nil t)
2911           (replace-match "" t t))))))
2912
2913 (defun message-make-date (&optional now)
2914   "Make a valid data header.
2915 If NOW, use that time instead."
2916   (let* ((now (or now (current-time)))
2917          (zone (nth 8 (decode-time now)))
2918          (sign "+"))
2919     (when (< zone 0)
2920       (setq sign "-")
2921       (setq zone (- zone)))
2922     (concat
2923      (format-time-string "%d" now)
2924      ;; The month name of the %b spec is locale-specific.  Pfff.
2925      (format " %s "
2926              (capitalize (car (rassoc (nth 4 (decode-time now))
2927                                       parse-time-months))))
2928      (format-time-string "%Y %H:%M:%S " now)
2929      ;; We do all of this because XEmacs doesn't have the %z spec.
2930      (format "%s%02d%02d" sign (/ zone 3600) (/ (% zone 3600) 60)))))
2931
2932 (defun message-make-message-id ()
2933   "Make a unique Message-ID."
2934   (concat "<" (message-unique-id)
2935           (let ((psubject (save-excursion (message-fetch-field "subject")))
2936                 (psupersedes
2937                  (save-excursion (message-fetch-field "supersedes"))))
2938             (if (or
2939                  (and message-reply-headers
2940                       (mail-header-references message-reply-headers)
2941                       (mail-header-subject message-reply-headers)
2942                       psubject
2943                       (mail-header-subject message-reply-headers)
2944                       (not (string=
2945                             (message-strip-subject-re
2946                              (mail-header-subject message-reply-headers))
2947                             (message-strip-subject-re psubject))))
2948                  (and psupersedes
2949                       (string-match "_-_@" psupersedes)))
2950                 "_-_" ""))
2951           "@" (message-make-fqdn) ">"))
2952
2953 (defvar message-unique-id-char nil)
2954
2955 ;; If you ever change this function, make sure the new version
2956 ;; cannot generate IDs that the old version could.
2957 ;; You might for example insert a "." somewhere (not next to another dot
2958 ;; or string boundary), or modify the "fsf" string.
2959 (defun message-unique-id ()
2960   ;; Don't use microseconds from (current-time), they may be unsupported.
2961   ;; Instead we use this randomly inited counter.
2962   (setq message-unique-id-char
2963         (% (1+ (or message-unique-id-char (logand (random t) (1- (lsh 1 20)))))
2964            ;; (current-time) returns 16-bit ints,
2965            ;; and 2^16*25 just fits into 4 digits i base 36.
2966            (* 25 25)))
2967   (let ((tm (current-time)))
2968     (concat
2969      (if (memq system-type '(ms-dos emx vax-vms))
2970          (let ((user (downcase (user-login-name))))
2971            (while (string-match "[^a-z0-9_]" user)
2972              (aset user (match-beginning 0) ?_))
2973            user)
2974        (message-number-base36 (user-uid) -1))
2975      (message-number-base36 (+ (car   tm)
2976                                (lsh (% message-unique-id-char 25) 16)) 4)
2977      (message-number-base36 (+ (nth 1 tm)
2978                                (lsh (/ message-unique-id-char 25) 16)) 4)
2979      ;; Append the newsreader name, because while the generated
2980      ;; ID is unique to this newsreader, other newsreaders might
2981      ;; otherwise generate the same ID via another algorithm.
2982      ".fsf")))
2983
2984 (defun message-number-base36 (num len)
2985   (if (if (< len 0)
2986           (<= num 0)
2987         (= len 0))
2988       ""
2989     (concat (message-number-base36 (/ num 36) (1- len))
2990             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
2991                                   (% num 36))))))
2992
2993 (defun message-make-organization ()
2994   "Make an Organization header."
2995   (let* ((organization
2996           (when message-user-organization
2997             (if (message-functionp message-user-organization)
2998                 (funcall message-user-organization)
2999               message-user-organization))))
3000     (save-excursion
3001       (message-set-work-buffer)
3002       (cond ((stringp organization)
3003              (insert organization))
3004             ((and (eq t organization)
3005                   message-user-organization-file
3006                   (file-exists-p message-user-organization-file))
3007              (insert-file-contents message-user-organization-file)))
3008       (goto-char (point-min))
3009       (while (re-search-forward "[\t\n]+" nil t)
3010         (replace-match "" t t))
3011       (unless (zerop (buffer-size))
3012         (buffer-string)))))
3013
3014 (defun message-make-lines ()
3015   "Count the number of lines and return numeric string."
3016   (save-excursion
3017     (save-restriction
3018       (widen)
3019       (goto-char (point-min))
3020       (re-search-forward
3021        (concat "^" (regexp-quote mail-header-separator) "$"))
3022       (forward-line 1)
3023       (int-to-string (count-lines (point) (point-max))))))
3024
3025 (defun message-make-in-reply-to ()
3026   "Return the In-Reply-To header for this message."
3027   (when message-reply-headers
3028     (let ((from (mail-header-from message-reply-headers))
3029           (date (mail-header-date message-reply-headers)))
3030       (when from
3031         (let ((stop-pos
3032                (string-match "  *at \\|  *@ \\| *(\\| *<" from)))
3033           (concat (if (and stop-pos
3034                            (not (zerop stop-pos)))
3035                       (substring from 0 stop-pos) from)
3036                   "'s message of \""
3037                   (if (or (not date) (string= date ""))
3038                       "(unknown date)" date)
3039                   "\""))))))
3040
3041 (defun message-make-distribution ()
3042   "Make a Distribution header."
3043   (let ((orig-distribution (message-fetch-reply-field "distribution")))
3044     (cond ((message-functionp message-distribution-function)
3045            (funcall message-distribution-function))
3046           (t orig-distribution))))
3047
3048 (defun message-make-expires ()
3049   "Return an Expires header based on `message-expires'."
3050   (let ((current (current-time))
3051         (future (* 1.0 message-expires 60 60 24)))
3052     ;; Add the future to current.
3053     (setcar current (+ (car current) (round (/ future (expt 2 16)))))
3054     (setcar (cdr current) (+ (nth 1 current) (% (round future) (expt 2 16))))
3055     (message-make-date current)))
3056
3057 (defun message-make-path ()
3058   "Return uucp path."
3059   (let ((login-name (user-login-name)))
3060     (cond ((null message-user-path)
3061            (concat (system-name) "!" login-name))
3062           ((stringp message-user-path)
3063            ;; Support GENERICPATH.  Suggested by vixie@decwrl.dec.com.
3064            (concat message-user-path "!" login-name))
3065           (t login-name))))
3066
3067 (defun message-make-from ()
3068   "Make a From header."
3069   (let* ((style message-from-style)
3070          (login (message-make-address))
3071          (fullname
3072           (or (and (boundp 'user-full-name)
3073                    user-full-name)
3074               (user-full-name))))
3075     (when (string= fullname "&")
3076       (setq fullname (user-login-name)))
3077     (save-excursion
3078       (message-set-work-buffer)
3079       (cond
3080        ((or (null style)
3081             (equal fullname ""))
3082         (insert login))
3083        ((or (eq style 'angles)
3084             (and (not (eq style 'parens))
3085                  ;; Use angles if no quoting is needed, or if parens would
3086                  ;; need quoting too.
3087                  (or (not (string-match "[^- !#-'*+/-9=?A-Z^-~]" fullname))
3088                      (let ((tmp (concat fullname nil)))
3089                        (while (string-match "([^()]*)" tmp)
3090                          (aset tmp (match-beginning 0) ?-)
3091                          (aset tmp (1- (match-end 0)) ?-))
3092                        (string-match "[\\()]" tmp)))))
3093         (insert fullname)
3094         (goto-char (point-min))
3095         ;; Look for a character that cannot appear unquoted
3096         ;; according to RFC 822.
3097         (when (re-search-forward "[^- !#-'*+/-9=?A-Z^-~]" nil 1)
3098           ;; Quote fullname, escaping specials.
3099           (goto-char (point-min))
3100           (insert "\"")
3101           (while (re-search-forward "[\"\\]" nil 1)
3102             (replace-match "\\\\\\&" t))
3103           (insert "\""))
3104         (insert " <" login ">"))
3105        (t                               ; 'parens or default
3106         (insert login " (")
3107         (let ((fullname-start (point)))
3108           (insert fullname)
3109           (goto-char fullname-start)
3110           ;; RFC 822 says \ and nonmatching parentheses
3111           ;; must be escaped in comments.
3112           ;; Escape every instance of ()\ ...
3113           (while (re-search-forward "[()\\]" nil 1)
3114             (replace-match "\\\\\\&" t))
3115           ;; ... then undo escaping of matching parentheses,
3116           ;; including matching nested parentheses.
3117           (goto-char fullname-start)
3118           (while (re-search-forward
3119                   "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
3120                   nil 1)
3121             (replace-match "\\1(\\3)" t)
3122             (goto-char fullname-start)))
3123         (insert ")")))
3124       (buffer-string))))
3125
3126 (defun message-make-sender ()
3127   "Return the \"real\" user address.
3128 This function tries to ignore all user modifications, and
3129 give as trustworthy answer as possible."
3130   (concat (user-login-name) "@" (system-name)))
3131
3132 (defun message-make-address ()
3133   "Make the address of the user."
3134   (or (message-user-mail-address)
3135       (concat (user-login-name) "@" (message-make-domain))))
3136
3137 (defun message-user-mail-address ()
3138   "Return the pertinent part of `user-mail-address'."
3139   (when user-mail-address
3140     (if (string-match " " user-mail-address)
3141         (nth 1 (mail-extract-address-components user-mail-address))
3142       user-mail-address)))
3143
3144 (defun message-make-fqdn ()
3145   "Return user's fully qualified domain name."
3146   (let ((system-name (system-name))
3147         (user-mail (message-user-mail-address)))
3148     (cond
3149      ((string-match "[^.]\\.[^.]" system-name)
3150       ;; `system-name' returned the right result.
3151       system-name)
3152      ;; Try `mail-host-address'.
3153      ((and (boundp 'mail-host-address)
3154            (stringp mail-host-address)
3155            (string-match "\\." mail-host-address))
3156       mail-host-address)
3157      ;; We try `user-mail-address' as a backup.
3158      ((and user-mail
3159            (string-match "\\." user-mail)
3160            (string-match "@\\(.*\\)\\'" user-mail))
3161       (match-string 1 user-mail))
3162      ;; Default to this bogus thing.
3163      (t
3164       (concat system-name ".i-did-not-set--mail-host-address--so-shoot-me")))))
3165
3166 (defun message-make-host-name ()
3167   "Return the name of the host."
3168   (let ((fqdn (message-make-fqdn)))
3169     (string-match "^[^.]+\\." fqdn)
3170     (substring fqdn 0 (1- (match-end 0)))))
3171
3172 (defun message-make-domain ()
3173   "Return the domain name."
3174   (or mail-host-address
3175       (message-make-fqdn)))
3176
3177 (defun message-generate-headers (headers)
3178   "Prepare article HEADERS.
3179 Headers already prepared in the buffer are not modified."
3180   (save-restriction
3181     (message-narrow-to-headers)
3182     (let* ((Date (message-make-date))
3183            (Message-ID (message-make-message-id))
3184            (Organization (message-make-organization))
3185            (From (message-make-from))
3186            (Path (message-make-path))
3187            (Subject nil)
3188            (Newsgroups nil)
3189            (In-Reply-To (message-make-in-reply-to))
3190            (To nil)
3191            (Distribution (message-make-distribution))
3192            (Lines (message-make-lines))
3193            (User-Agent message-newsreader)
3194            (Expires (message-make-expires))
3195            (case-fold-search t)
3196            header value elem)
3197       ;; First we remove any old generated headers.
3198       (let ((headers message-deletable-headers))
3199         (unless (buffer-modified-p)
3200           (setq headers (delq 'Message-ID (copy-sequence headers))))
3201         (while headers
3202           (goto-char (point-min))
3203           (and (re-search-forward
3204                 (concat "^" (symbol-name (car headers)) ": *") nil t)
3205                (get-text-property (1+ (match-beginning 0)) 'message-deletable)
3206                (message-delete-line))
3207           (pop headers)))
3208       ;; Go through all the required headers and see if they are in the
3209       ;; articles already.  If they are not, or are empty, they are
3210       ;; inserted automatically - except for Subject, Newsgroups and
3211       ;; Distribution.
3212       (while headers
3213         (goto-char (point-min))
3214         (setq elem (pop headers))
3215         (if (consp elem)
3216             (if (eq (car elem) 'optional)
3217                 (setq header (cdr elem))
3218               (setq header (car elem)))
3219           (setq header elem))
3220         (when (or (not (re-search-forward
3221                         (concat "^"
3222                                 (regexp-quote
3223                                  (downcase
3224                                   (if (stringp header)
3225                                       header
3226                                     (symbol-name header))))
3227                                 ":")
3228                         nil t))
3229                   (progn
3230                     ;; The header was found.  We insert a space after the
3231                     ;; colon, if there is none.
3232                     (if (/= (char-after) ? ) (insert " ") (forward-char 1))
3233                     ;; Find out whether the header is empty...
3234                     (looking-at "[ \t]*\n[^ \t]")))
3235           ;; So we find out what value we should insert.
3236           (setq value
3237                 (cond
3238                  ((and (consp elem) (eq (car elem) 'optional))
3239                   ;; This is an optional header.  If the cdr of this
3240                   ;; is something that is nil, then we do not insert
3241                   ;; this header.
3242                   (setq header (cdr elem))
3243                   (or (and (fboundp (cdr elem)) (funcall (cdr elem)))
3244                       (and (boundp (cdr elem)) (symbol-value (cdr elem)))))
3245                  ((consp elem)
3246                   ;; The element is a cons.  Either the cdr is a
3247                   ;; string to be inserted verbatim, or it is a
3248                   ;; function, and we insert the value returned from
3249                   ;; this function.
3250                   (or (and (stringp (cdr elem)) (cdr elem))
3251                       (and (fboundp (cdr elem)) (funcall (cdr elem)))))
3252                  ((and (boundp header) (symbol-value header))
3253                   ;; The element is a symbol.  We insert the value
3254                   ;; of this symbol, if any.
3255                   (symbol-value header))
3256                  ((not (message-check-element header))
3257                   ;; We couldn't generate a value for this header,
3258                   ;; so we just ask the user.
3259                   (read-from-minibuffer
3260                    (format "Empty header for %s; enter value: " header)))))
3261           ;; Finally insert the header.
3262           (when (and value
3263                      (not (equal value "")))
3264             (save-excursion
3265               (if (bolp)
3266                   (progn
3267                     ;; This header didn't exist, so we insert it.
3268                     (goto-char (point-max))
3269                     (insert (if (stringp header) header (symbol-name header))
3270                             ": " value "\n")
3271                     (forward-line -1))
3272                 ;; The value of this header was empty, so we clear
3273                 ;; totally and insert the new value.
3274                 (delete-region (point) (gnus-point-at-eol))
3275                 (insert value))
3276               ;; Add the deletable property to the headers that require it.
3277               (and (memq header message-deletable-headers)
3278                    (progn (beginning-of-line) (looking-at "[^:]+: "))
3279                    (add-text-properties
3280                     (point) (match-end 0)
3281                     '(message-deletable t face italic) (current-buffer)))))))
3282       ;; Insert new Sender if the From is strange.
3283       (let ((from (message-fetch-field "from"))
3284             (sender (message-fetch-field "sender"))
3285             (secure-sender (message-make-sender)))
3286         (when (and from
3287                    (not (message-check-element 'sender))
3288                    (not (string=
3289                          (downcase
3290                           (cadr (mail-extract-address-components from)))
3291                          (downcase secure-sender)))
3292                    (or (null sender)
3293                        (not
3294                         (string=
3295                          (downcase
3296                           (cadr (mail-extract-address-components sender)))
3297                          (downcase secure-sender)))))
3298           (goto-char (point-min))
3299           ;; Rename any old Sender headers to Original-Sender.
3300           (when (re-search-forward "^\\(Original-\\)*Sender:" nil t)
3301             (beginning-of-line)
3302             (insert "Original-")
3303             (beginning-of-line))
3304           (when (or (message-news-p)
3305                     (string-match "@.+\\.." secure-sender))
3306             (insert "Sender: " secure-sender "\n")))))))
3307
3308 (defun message-insert-courtesy-copy ()
3309   "Insert a courtesy message in mail copies of combined messages."
3310   (let (newsgroups)
3311     (save-excursion
3312       (save-restriction
3313         (message-narrow-to-headers)
3314         (when (setq newsgroups (message-fetch-field "newsgroups"))
3315           (goto-char (point-max))
3316           (insert "Posted-To: " newsgroups "\n")))
3317       (forward-line 1)
3318       (when message-courtesy-message
3319         (cond
3320          ((string-match "%s" message-courtesy-message)
3321           (insert (format message-courtesy-message newsgroups)))
3322          (t
3323           (insert message-courtesy-message)))))))
3324
3325 ;;;
3326 ;;; Setting up a message buffer
3327 ;;;
3328
3329 (defun message-fill-address (header value)
3330   (save-restriction
3331     (narrow-to-region (point) (point))
3332     (insert (capitalize (symbol-name header))
3333             ": "
3334             (if (consp value) (car value) value)
3335             "\n")
3336     (narrow-to-region (point-min) (1- (point-max)))
3337     (let (quoted last)
3338       (goto-char (point-min))
3339       (while (not (eobp))
3340         (skip-chars-forward "^,\"" (point-max))
3341         (if (or (eq (char-after) ?,)
3342                 (eobp))
3343             (when (not quoted)
3344               (if (and (> (current-column) 78)
3345                        last)
3346                   (progn
3347                     (save-excursion
3348                       (goto-char last)
3349                       (insert "\n\t"))
3350                     (setq last (1+ (point))))
3351                 (setq last (1+ (point)))))
3352           (setq quoted (not quoted)))
3353         (unless (eobp)
3354           (forward-char 1))))
3355     (goto-char (point-max))
3356     (widen)
3357     (forward-line 1)))
3358
3359 (defun message-fill-header (header value)
3360   (let ((begin (point))
3361         (fill-column 78)
3362         (fill-prefix "\t"))
3363     (insert (capitalize (symbol-name header))
3364             ": "
3365             (if (consp value) (car value) value)
3366             "\n")
3367     (save-restriction
3368       (narrow-to-region begin (point))
3369       (fill-region-as-paragraph begin (point))
3370       ;; Tapdance around looong Message-IDs.
3371       (forward-line -1)
3372       (when (looking-at "[ \t]*$")
3373         (message-delete-line))
3374       (goto-char begin)
3375       (re-search-forward ":" nil t)
3376       (when (looking-at "\n[ \t]+")
3377         (replace-match " " t t))
3378       (goto-char (point-max)))))
3379
3380 (defun message-shorten-1 (list cut surplus)
3381   ;; Cut SURPLUS elements out of LIST, beginning with CUTth one.
3382   (setcdr (nthcdr (- cut 2) list)
3383           (nthcdr (+ (- cut 2) surplus 1) list)))
3384
3385 (defun message-shorten-references (header references)
3386   "Trim REFERENCES to be less than 31 Message-ID long, and fold them.
3387 If folding is disallowed, also check that the REFERENCES are less
3388 than 988 characters long, and if they are not, trim them until they are."
3389   (let ((maxcount 31)
3390         (count 0)
3391         (cut 6)
3392         refs)
3393     (with-temp-buffer
3394       (insert references)
3395       (goto-char (point-min))
3396       ;; Cons a list of valid references.
3397       (while (re-search-forward "<[^>]+>" nil t)
3398         (push (match-string 0) refs))
3399       (setq refs (nreverse refs)
3400             count (length refs)))
3401
3402     ;; If the list has more than MAXCOUNT elements, trim it by
3403     ;; removing the CUTth element and the required number of
3404     ;; elements that follow.
3405     (when (> count maxcount)
3406       (let ((surplus (- count maxcount)))
3407         (message-shorten-1 refs cut surplus)
3408         (decf count surplus)))
3409
3410     ;; If folding is disallowed, make sure the total length (including
3411     ;; the spaces between) will be less than MAXSIZE characters.
3412     ;;
3413     ;; Only disallow folding for News messages. At this point the headers
3414     ;; have not been generated, thus we use message-this-is-news directly.
3415     (when (and message-this-is-news message-cater-to-broken-inn)
3416       (let ((maxsize 988)
3417             (totalsize (+ (apply #'+ (mapcar #'length refs))
3418                           (1- count)))
3419             (surplus 0)
3420             (ptr (nthcdr (1- cut) refs)))
3421         ;; Decide how many elements to cut off...
3422         (while (> totalsize maxsize)
3423           (decf totalsize (1+ (length (car ptr))))
3424           (incf surplus)
3425           (setq ptr (cdr ptr)))
3426         ;; ...and do it.
3427         (when (> surplus 0)
3428           (message-shorten-1 refs cut surplus))))
3429
3430     ;; Finally, collect the references back into a string and insert
3431     ;; it into the buffer.
3432     (let ((refstring (mapconcat #'identity refs " ")))
3433       (if (and message-this-is-news message-cater-to-broken-inn)
3434           (insert (capitalize (symbol-name header)) ": "
3435                   refstring "\n")
3436         (message-fill-header header refstring)))))
3437
3438 (defun message-position-point ()
3439   "Move point to where the user probably wants to find it."
3440   (message-narrow-to-headers)
3441   (cond
3442    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
3443     (search-backward ":" )
3444     (widen)
3445     (forward-char 1)
3446     (if (eq (char-after) ? )
3447         (forward-char 1)
3448       (insert " ")))
3449    (t
3450     (goto-char (point-max))
3451     (widen)
3452     (forward-line 1)
3453     (unless (looking-at "$")
3454       (forward-line 2)))
3455    (sit-for 0)))
3456
3457 (defun message-buffer-name (type &optional to group)
3458   "Return a new (unique) buffer name based on TYPE and TO."
3459   (cond
3460    ;; Generate a new buffer name The Message Way.
3461    ((eq message-generate-new-buffers 'unique)
3462     (generate-new-buffer-name
3463      (concat "*" type
3464              (if to
3465                  (concat " to "
3466                          (or (car (mail-extract-address-components to))
3467                              to) "")
3468                "")
3469              (if (and group (not (string= group ""))) (concat " on " group) "")
3470              "*")))
3471    ;; Check whether `message-generate-new-buffers' is a function,
3472    ;; and if so, call it.
3473    ((message-functionp message-generate-new-buffers)
3474     (funcall message-generate-new-buffers type to group))
3475    ((eq message-generate-new-buffers 'unsent)
3476     (generate-new-buffer-name
3477      (concat "*unsent " type
3478              (if to
3479                  (concat " to "
3480                          (or (car (mail-extract-address-components to))
3481                              to) "")
3482                "")
3483              (if (and group (not (string= group ""))) (concat " on " group) "")
3484              "*")))
3485    ;; Use standard name.
3486    (t
3487     (format "*%s message*" type))))
3488
3489 (defun message-pop-to-buffer (name)
3490   "Pop to buffer NAME, and warn if it already exists and is modified."
3491   (let ((buffer (get-buffer name)))
3492     (if (and buffer
3493              (buffer-name buffer))
3494         (progn
3495           (set-buffer (pop-to-buffer buffer))
3496           (when (and (buffer-modified-p)
3497                      (not (y-or-n-p
3498                            "Message already being composed; erase? ")))
3499             (error "Message being composed")))
3500       (set-buffer (pop-to-buffer name)))
3501     (erase-buffer)
3502     (message-mode)))
3503
3504 (defun message-do-send-housekeeping ()
3505   "Kill old message buffers."
3506   ;; We might have sent this buffer already.  Delete it from the
3507   ;; list of buffers.
3508   (setq message-buffer-list (delq (current-buffer) message-buffer-list))
3509   (while (and message-max-buffers
3510               message-buffer-list
3511               (>= (length message-buffer-list) message-max-buffers))
3512     ;; Kill the oldest buffer -- unless it has been changed.
3513     (let ((buffer (pop message-buffer-list)))
3514       (when (and (buffer-name buffer)
3515                  (not (buffer-modified-p buffer)))
3516         (kill-buffer buffer))))
3517   ;; Rename the buffer.
3518   (if message-send-rename-function
3519       (funcall message-send-rename-function)
3520     (when (string-match "\\`\\*\\(unsent \\)?" (buffer-name))
3521       (rename-buffer
3522        (concat "*sent " (substring (buffer-name) (match-end 0))) t)))
3523   ;; Push the current buffer onto the list.
3524   (when message-max-buffers
3525     (setq message-buffer-list
3526           (nconc message-buffer-list (list (current-buffer))))))
3527
3528 (defvar mc-modes-alist)
3529 (defun message-setup (headers &optional replybuffer actions)
3530   (when (and (boundp 'mc-modes-alist)
3531              (not (assq 'message-mode mc-modes-alist)))
3532     (push '(message-mode (encrypt . mc-encrypt-message)
3533                          (sign . mc-sign-message))
3534           mc-modes-alist))
3535   (when actions
3536     (setq message-send-actions actions))
3537   (setq message-reply-buffer replybuffer)
3538   (goto-char (point-min))
3539   ;; Insert all the headers.
3540   (mail-header-format
3541    (let ((h headers)
3542          (alist message-header-format-alist))
3543      (while h
3544        (unless (assq (caar h) message-header-format-alist)
3545          (push (list (caar h)) alist))
3546        (pop h))
3547      alist)
3548    headers)
3549   (delete-region (point) (progn (forward-line -1) (point)))
3550   (when message-default-headers
3551     (insert message-default-headers)
3552     (or (bolp) (insert ?\n)))
3553   (put-text-property
3554    (point)
3555    (progn
3556      (insert mail-header-separator "\n")
3557      (1- (point)))
3558    'read-only nil)
3559   (forward-line -1)
3560   (when (message-news-p)
3561     (when message-default-news-headers
3562       (insert message-default-news-headers)
3563       (or (bolp) (insert ?\n)))
3564     (when message-generate-headers-first
3565       (message-generate-headers
3566        (delq 'Lines
3567              (delq 'Subject
3568                    (copy-sequence message-required-news-headers))))))
3569   (when (message-mail-p)
3570     (when message-default-mail-headers
3571       (insert message-default-mail-headers)
3572       (or (bolp) (insert ?\n)))
3573     (when message-generate-headers-first
3574       (message-generate-headers
3575        (delq 'Lines
3576              (delq 'Subject
3577                    (copy-sequence message-required-mail-headers))))))
3578   (run-hooks 'message-signature-setup-hook)
3579   (message-insert-signature)
3580   (save-restriction
3581     (message-narrow-to-headers)
3582     (run-hooks 'message-header-setup-hook))
3583   (set-buffer-modified-p nil)
3584   (setq buffer-undo-list nil)
3585   (run-hooks 'message-setup-hook)
3586   (message-position-point)
3587   (undo-boundary))
3588
3589 (defun message-set-auto-save-file-name ()
3590   "Associate the message buffer with a file in the drafts directory."
3591   (when message-auto-save-directory
3592     (if (gnus-alive-p)
3593         (setq message-draft-article
3594               (nndraft-request-associate-buffer "drafts"))
3595       (setq buffer-file-name (expand-file-name "*message*"
3596                                                message-auto-save-directory))
3597       (setq buffer-auto-save-file-name (make-auto-save-file-name)))
3598     (clear-visited-file-modtime)
3599     (setq buffer-file-coding-system message-draft-coding-system)))
3600
3601 (defun message-disassociate-draft ()
3602   "Disassociate the message buffer from the drafts directory."
3603   (when message-draft-article
3604     (nndraft-request-expire-articles
3605      (list message-draft-article) "drafts" nil t)))
3606
3607 (defun message-insert-headers ()
3608   "Generate the headers for the article."
3609   (interactive)
3610   (save-excursion
3611     (save-restriction
3612       (message-narrow-to-headers)
3613       (when (message-news-p)
3614         (message-generate-headers
3615          (delq 'Lines
3616                (delq 'Subject
3617                      (copy-sequence message-required-news-headers)))))
3618       (when (message-mail-p)
3619         (message-generate-headers
3620          (delq 'Lines
3621                (delq 'Subject
3622                      (copy-sequence message-required-mail-headers))))))))
3623
3624 \f
3625
3626 ;;;
3627 ;;; Commands for interfacing with message
3628 ;;;
3629
3630 ;;;###autoload
3631 (defun message-mail (&optional to subject
3632                                other-headers continue switch-function
3633                                yank-action send-actions)
3634   "Start editing a mail message to be sent.
3635 OTHER-HEADERS is an alist of header/value pairs."
3636   (interactive)
3637   (let ((message-this-is-mail t))
3638     (message-pop-to-buffer (message-buffer-name "mail" to))
3639     (message-setup
3640      (nconc
3641       `((To . ,(or to "")) (Subject . ,(or subject "")))
3642       (when other-headers other-headers)))))
3643
3644 ;;;###autoload
3645 (defun message-news (&optional newsgroups subject)
3646   "Start editing a news article to be sent."
3647   (interactive)
3648   (let ((message-this-is-news t))
3649     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups))
3650     (message-setup `((Newsgroups . ,(or newsgroups ""))
3651                      (Subject . ,(or subject ""))))))
3652
3653 (defun message-get-reply-headers (wide &optional to-address)
3654   (let (follow-to mct never-mct from to cc reply-to ccalist)
3655     ;; Find all relevant headers we need.
3656     (setq from (message-fetch-field "from")
3657           to (message-fetch-field "to")
3658           cc (message-fetch-field "cc")
3659           mct (message-fetch-field "mail-copies-to")
3660           reply-to (message-fetch-field "reply-to"))
3661
3662     ;; Handle special values of Mail-Copies-To.
3663     (when mct
3664       (cond ((or (equal (downcase mct) "never")
3665                  (equal (downcase mct) "nobody"))
3666              (setq never-mct t)
3667              (setq mct nil))
3668             ((or (equal (downcase mct) "always")
3669                  (equal (downcase mct) "poster"))
3670              (setq mct (or reply-to from)))))
3671
3672     (if (or (not wide)
3673             to-address)
3674         (progn
3675           (setq follow-to (list (cons 'To (or to-address reply-to from))))
3676           (when (and wide mct)
3677             (push (cons 'Cc mct) follow-to)))
3678       (let (ccalist)
3679         (save-excursion
3680           (message-set-work-buffer)
3681           (unless never-mct
3682             (insert (or reply-to from "")))
3683           (insert (if to (concat (if (bolp) "" ", ") to "") ""))
3684           (insert (if mct (concat (if (bolp) "" ", ") mct) ""))
3685           (insert (if cc (concat (if (bolp) "" ", ") cc) ""))
3686           (goto-char (point-min))
3687           (while (re-search-forward "[ \t]+" nil t)
3688             (replace-match " " t t))
3689           ;; Remove addresses that match `rmail-dont-reply-to-names'.
3690           (let ((rmail-dont-reply-to-names message-dont-reply-to-names))
3691             (insert (prog1 (rmail-dont-reply-to (buffer-string))
3692                       (erase-buffer))))
3693           (goto-char (point-min))
3694           ;; Perhaps "Mail-Copies-To: never" removed the only address?
3695           (when (eobp)
3696             (insert (or reply-to from "")))
3697           (setq ccalist
3698                 (mapcar
3699                  (lambda (addr)
3700                    (cons (mail-strip-quoted-names addr) addr))
3701                  (message-tokenize-header (buffer-string))))
3702           (let ((s ccalist))
3703             (while s
3704               (setq ccalist (delq (assoc (car (pop s)) s) ccalist)))))
3705         (setq follow-to (list (cons 'To (cdr (pop ccalist)))))
3706         (when ccalist
3707           (let ((ccs (cons 'Cc (mapconcat
3708                                 (lambda (addr) (cdr addr)) ccalist ", "))))
3709             (when (string-match "^ +" (cdr ccs))
3710               (setcdr ccs (substring (cdr ccs) (match-end 0))))
3711             (push ccs follow-to)))))
3712     follow-to))
3713
3714
3715 ;;;###autoload
3716 (defun message-reply (&optional to-address wide)
3717   "Start editing a reply to the article in the current buffer."
3718   (interactive)
3719   (require 'gnus-sum)                   ; for gnus-list-identifiers
3720   (let ((cur (current-buffer))
3721         from subject date reply-to to cc
3722         references message-id follow-to
3723         (inhibit-point-motion-hooks t)
3724         (message-this-is-mail t)
3725         gnus-warning)
3726     (save-restriction
3727       (message-narrow-to-head)
3728       ;; Allow customizations to have their say.
3729       (if (not wide)
3730           ;; This is a regular reply.
3731           (if (message-functionp message-reply-to-function)
3732               (setq follow-to (funcall message-reply-to-function)))
3733         ;; This is a followup.
3734         (if (message-functionp message-wide-reply-to-function)
3735             (save-excursion
3736               (setq follow-to
3737                     (funcall message-wide-reply-to-function)))))
3738       (setq message-id (message-fetch-field "message-id" t)
3739             references (message-fetch-field "references")
3740             date (message-fetch-field "date")
3741             from (message-fetch-field "from")
3742             subject (or (message-fetch-field "subject") "none"))
3743     (if gnus-list-identifiers
3744         (setq subject (message-strip-list-identifiers subject)))
3745     (setq subject (concat "Re: " (message-strip-subject-re subject)))
3746
3747     (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
3748                (string-match "<[^>]+>" gnus-warning))
3749       (setq message-id (match-string 0 gnus-warning)))
3750
3751     (unless follow-to
3752       (setq follow-to (message-get-reply-headers wide to-address))))
3753
3754     (message-pop-to-buffer
3755      (message-buffer-name
3756       (if wide "wide reply" "reply") from
3757       (if wide to-address nil)))
3758
3759     (setq message-reply-headers
3760           (vector 0 subject from date message-id references 0 0 ""))
3761
3762     (message-setup
3763      `((Subject . ,subject)
3764        ,@follow-to
3765        ,@(if (or references message-id)
3766              `((References . ,(concat (or references "") (and references " ")
3767                                       (or message-id ""))))
3768            nil))
3769      cur)))
3770
3771 ;;;###autoload
3772 (defun message-wide-reply (&optional to-address)
3773   "Make a \"wide\" reply to the message in the current buffer."
3774   (interactive)
3775   (message-reply to-address t))
3776
3777 ;;;###autoload
3778 (defun message-followup (&optional to-newsgroups)
3779   "Follow up to the message in the current buffer.
3780 If TO-NEWSGROUPS, use that as the new Newsgroups line."
3781   (interactive)
3782   (require 'gnus-sum)                   ; for gnus-list-identifiers
3783   (let ((cur (current-buffer))
3784         from subject date reply-to mct
3785         references message-id follow-to
3786         (inhibit-point-motion-hooks t)
3787         (message-this-is-news t)
3788         followup-to distribution newsgroups gnus-warning posted-to)
3789     (save-restriction
3790       (narrow-to-region
3791        (goto-char (point-min))
3792        (if (search-forward "\n\n" nil t)
3793            (1- (point))
3794          (point-max)))
3795       (when (message-functionp message-followup-to-function)
3796         (setq follow-to
3797               (funcall message-followup-to-function)))
3798       (setq from (message-fetch-field "from")
3799             date (message-fetch-field "date")
3800             subject (or (message-fetch-field "subject") "none")
3801             references (message-fetch-field "references")
3802             message-id (message-fetch-field "message-id" t)
3803             followup-to (message-fetch-field "followup-to")
3804             newsgroups (message-fetch-field "newsgroups")
3805             posted-to (message-fetch-field "posted-to")
3806             reply-to (message-fetch-field "reply-to")
3807             distribution (message-fetch-field "distribution")
3808             mct (message-fetch-field "mail-copies-to"))
3809       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
3810                  (string-match "<[^>]+>" gnus-warning))
3811         (setq message-id (match-string 0 gnus-warning)))
3812       ;; Remove bogus distribution.
3813       (when (and (stringp distribution)
3814                  (let ((case-fold-search t))
3815                    (string-match "world" distribution)))
3816         (setq distribution nil))
3817       (if gnus-list-identifiers
3818           (setq subject (message-strip-list-identifiers subject)))
3819       (setq subject (concat "Re: " (message-strip-subject-re subject)))
3820       (widen))
3821
3822     (message-pop-to-buffer (message-buffer-name "followup" from newsgroups))
3823
3824     (message-setup
3825      `((Subject . ,subject)
3826        ,@(cond
3827           (to-newsgroups
3828            (list (cons 'Newsgroups to-newsgroups)))
3829           (follow-to follow-to)
3830           ((and followup-to message-use-followup-to)
3831            (list
3832             (cond
3833              ((equal (downcase followup-to) "poster")
3834               (if (or (eq message-use-followup-to 'use)
3835                       (message-y-or-n-p "Obey Followup-To: poster? " t "\
3836 You should normally obey the Followup-To: header.
3837
3838 `Followup-To: poster' sends your response via e-mail instead of news.
3839
3840 A typical situation where `Followup-To: poster' is used is when the poster
3841 does not read the newsgroup, so he wouldn't see any replies sent to it."))
3842                   (progn
3843                     (setq message-this-is-news nil)
3844                     (cons 'To (or reply-to from "")))
3845                 (cons 'Newsgroups newsgroups)))
3846              (t
3847               (if (or (equal followup-to newsgroups)
3848                       (not (eq message-use-followup-to 'ask))
3849                       (message-y-or-n-p
3850                        (concat "Obey Followup-To: " followup-to "? ") t "\
3851 You should normally obey the Followup-To: header.
3852
3853         `Followup-To: " followup-to "'
3854 directs your response to " (if (string-match "," followup-to)
3855                                "the specified newsgroups"
3856                              "that newsgroup only") ".
3857
3858 If a message is posted to several newsgroups, Followup-To is often
3859 used to direct the following discussion to one newsgroup only,
3860 because discussions that are spread over several newsgroup tend to
3861 be fragmented and very difficult to follow.
3862
3863 Also, some source/announcement newsgroups are not indented for discussion;
3864 responses here are directed to other newsgroups."))
3865                   (cons 'Newsgroups followup-to)
3866                 (cons 'Newsgroups newsgroups))))))
3867           (posted-to
3868            `((Newsgroups . ,posted-to)))
3869           (t
3870            `((Newsgroups . ,newsgroups))))
3871        ,@(and distribution (list (cons 'Distribution distribution)))
3872        ,@(if (or references message-id)
3873              `((References . ,(concat (or references "") (and references " ")
3874                                       (or message-id "")))))
3875        ,@(when (and mct
3876                     (not (or (equal (downcase mct) "never")
3877                              (equal (downcase mct) "nobody"))))
3878            (list (cons 'Cc (if (or (equal (downcase mct) "always")
3879                                    (equal (downcase mct) "poster"))
3880                                (or reply-to from "")
3881                              mct)))))
3882
3883      cur)
3884
3885     (setq message-reply-headers
3886           (vector 0 subject from date message-id references 0 0 ""))))
3887
3888
3889 ;;;###autoload
3890 (defun message-cancel-news (&optional arg)
3891   "Cancel an article you posted.
3892 If ARG, allow editing of the cancellation message."
3893   (interactive "P")
3894   (unless (message-news-p)
3895     (error "This is not a news article; canceling is impossible"))
3896   (when (yes-or-no-p "Do you really want to cancel this article? ")
3897     (let (from newsgroups message-id distribution buf sender)
3898       (save-excursion
3899         ;; Get header info from original article.
3900         (save-restriction
3901           (message-narrow-to-head)
3902           (setq from (message-fetch-field "from")
3903                 sender (message-fetch-field "sender")
3904                 newsgroups (message-fetch-field "newsgroups")
3905                 message-id (message-fetch-field "message-id" t)
3906                 distribution (message-fetch-field "distribution")))
3907         ;; Make sure that this article was written by the user.
3908         (unless (or (and sender
3909                          (string-equal
3910                           (downcase sender)
3911                           (downcase (message-make-sender))))
3912                     (string-equal
3913                      (downcase (cadr (mail-extract-address-components from)))
3914                      (downcase (cadr (mail-extract-address-components
3915                                       (message-make-from))))))
3916           (error "This article is not yours"))
3917         ;; Make control message.
3918         (if arg
3919             (message-news)
3920           (setq buf (set-buffer (get-buffer-create " *message cancel*"))))
3921         (erase-buffer)
3922         (insert "Newsgroups: " newsgroups "\n"
3923                "From: " from "\n"
3924                 "Subject: cmsg cancel " message-id "\n"
3925                 "Control: cancel " message-id "\n"
3926                 (if distribution
3927                     (concat "Distribution: " distribution "\n")
3928                   "")
3929                 mail-header-separator "\n"
3930                 message-cancel-message)
3931         (run-hooks 'message-cancel-hook)
3932         (unless arg
3933           (message "Canceling your article...")
3934           (if (let ((message-syntax-checks
3935                      'dont-check-for-anything-just-trust-me))
3936                 (funcall message-send-news-function))
3937               (message "Canceling your article...done"))
3938           (kill-buffer buf))))))
3939
3940 ;;;###autoload
3941 (defun message-supersede ()
3942   "Start composing a message to supersede the current message.
3943 This is done simply by taking the old article and adding a Supersedes
3944 header line with the old Message-ID."
3945   (interactive)
3946   (let ((cur (current-buffer))
3947         (sender (message-fetch-field "sender"))
3948         (from (message-fetch-field "from")))
3949     ;; Check whether the user owns the article that is to be superseded.
3950     (unless (or (and sender
3951                      (string-equal
3952                       (downcase sender)
3953                       (downcase (message-make-sender))))
3954                 (string-equal
3955                  (downcase (cadr (mail-extract-address-components from)))
3956                  (downcase (cadr (mail-extract-address-components
3957                                   (message-make-from))))))
3958       (error "This article is not yours"))
3959     ;; Get a normal message buffer.
3960     (message-pop-to-buffer (message-buffer-name "supersede"))
3961     (insert-buffer-substring cur)
3962     (mime-to-mml)
3963     (message-narrow-to-head)
3964     ;; Remove unwanted headers.
3965     (when message-ignored-supersedes-headers
3966       (message-remove-header message-ignored-supersedes-headers t))
3967     (goto-char (point-min))
3968     (if (not (re-search-forward "^Message-ID: " nil t))
3969         (error "No Message-ID in this article")
3970       (replace-match "Supersedes: " t t))
3971     (goto-char (point-max))
3972     (insert mail-header-separator)
3973     (widen)
3974     (forward-line 1)))
3975
3976 ;;;###autoload
3977 (defun message-recover ()
3978   "Reread contents of current buffer from its last auto-save file."
3979   (interactive)
3980   (let ((file-name (make-auto-save-file-name)))
3981     (cond ((save-window-excursion
3982              (if (not (eq system-type 'vax-vms))
3983                  (with-output-to-temp-buffer "*Directory*"
3984                    (with-current-buffer standard-output
3985                      (fundamental-mode)) ; for Emacs 20.4+
3986                    (buffer-disable-undo standard-output)
3987                    (let ((default-directory "/"))
3988                      (call-process
3989                       "ls" nil standard-output nil "-l" file-name))))
3990              (yes-or-no-p (format "Recover auto save file %s? " file-name)))
3991            (let ((buffer-read-only nil))
3992              (erase-buffer)
3993              (insert-file-contents file-name nil)))
3994           (t (error "message-recover cancelled")))))
3995
3996 ;;; Washing Subject:
3997
3998 (defun message-wash-subject (subject)
3999   "Remove junk like \"Re:\", \"(fwd)\", etc. that was added to the subject by previous forwarders, replyers, etc."
4000   (with-temp-buffer
4001     (insert-string subject)
4002     (goto-char (point-min))
4003     ;; strip Re/Fwd stuff off the beginning
4004     (while (re-search-forward
4005             "\\([Rr][Ee]:\\|[Ff][Ww][Dd]\\(\\[[0-9]*\\]\\)?:\\|[Ff][Ww]:\\)" nil t)
4006       (replace-match ""))
4007
4008     ;; and gnus-style forwards [foo@bar.com] subject
4009     (goto-char (point-min))
4010     (while (re-search-forward "\\[[^ \t]*\\(@\\|\\.\\)[^ \t]*\\]" nil t)
4011       (replace-match ""))
4012
4013     ;; and off the end
4014     (goto-char (point-max))
4015     (while (re-search-backward "([Ff][Ww][Dd])" nil t)
4016       (replace-match ""))
4017
4018     ;; and finally, any whitespace that was left-over
4019     (goto-char (point-min))
4020     (while (re-search-forward "^[ \t]+" nil t)
4021       (replace-match ""))
4022     (goto-char (point-max))
4023     (while (re-search-backward "[ \t]+$" nil t)
4024       (replace-match ""))
4025
4026     (buffer-string)))
4027
4028 ;;; Forwarding messages.
4029
4030 (defun message-forward-subject-author-subject (subject)
4031   "Generate a subject for a forwarded message.
4032 The form is: [Source] Subject, where if the original message was mail,
4033 Source is the sender, and if the original message was news, Source is
4034 the list of newsgroups is was posted to."
4035   (concat "["
4036           (or (message-fetch-field
4037                (if (message-news-p) "newsgroups" "from"))
4038               "(nowhere)")
4039           "] " subject))
4040
4041 (defun message-forward-subject-fwd (subject)
4042   "Generate a subject for a forwarded message.
4043 The form is: Fwd: Subject, where Subject is the original subject of
4044 the message."
4045   (concat "Fwd: " subject))
4046
4047 (defun message-make-forward-subject ()
4048   "Return a Subject header suitable for the message in the current buffer."
4049   (save-excursion
4050     (save-restriction
4051       (current-buffer)
4052       (message-narrow-to-head)
4053       (let ((funcs message-make-forward-subject-function)
4054             (subject (if message-wash-forwarded-subjects
4055                          (message-wash-subject
4056                           (or (message-fetch-field "Subject") ""))
4057                        (or (message-fetch-field "Subject") ""))))
4058         ;; Make sure funcs is a list.
4059         (and funcs
4060              (not (listp funcs))
4061              (setq funcs (list funcs)))
4062         ;; Apply funcs in order, passing subject generated by previous
4063         ;; func to the next one.
4064         (while funcs
4065           (when (message-functionp (car funcs))
4066             (setq subject (funcall (car funcs) subject)))
4067           (setq funcs (cdr funcs)))
4068         subject))))
4069
4070 ;;;###autoload
4071 (defun message-forward (&optional news digest)
4072   "Forward the current message via mail.
4073 Optional NEWS will use news to forward instead of mail.
4074 Optional DIGEST will use digest to forward."
4075   (interactive "P")
4076   (let* ((cur (current-buffer))
4077          (subject (if message-forward-show-mml
4078                       (message-make-forward-subject)
4079                     (mail-decode-encoded-word-string
4080                      (message-make-forward-subject))))
4081          art-beg)
4082     (if news
4083         (message-news nil subject)
4084       (message-mail nil subject))
4085     ;; Put point where we want it before inserting the forwarded
4086     ;; message.
4087     (if message-forward-before-signature
4088         (message-goto-body)
4089       (goto-char (point-max)))
4090     (if message-forward-as-mime
4091         (if digest
4092             (insert "\n<#multipart type=digest>\n")
4093           (if message-forward-show-mml
4094               (insert "\n\n<#mml type=message/rfc822 disposition=inline>\n")
4095             (insert "\n\n<#part type=message/rfc822 disposition=inline raw=t>\n")))
4096       (insert "\n-------------------- Start of forwarded message --------------------\n"))
4097     (let ((b (point)) e)
4098       (if digest
4099           (if message-forward-as-mime
4100               (insert-buffer-substring cur)
4101             (mml-insert-buffer cur))
4102         (if message-forward-show-mml
4103             (insert-buffer-substring cur)
4104           (mm-with-unibyte-current-buffer
4105             (mml-insert-buffer cur))))
4106       (setq e (point))
4107       (if message-forward-as-mime
4108           (if digest
4109               (insert "<#/multipart>\n")
4110             (if message-forward-show-mml
4111                 (insert "<#/mml>\n")
4112               (insert "<#/part>\n")))
4113         (insert "\n-------------------- End of forwarded message --------------------\n"))
4114       (if (and digest message-forward-as-mime)
4115           (save-restriction
4116             (narrow-to-region b e)
4117             (goto-char b)
4118             (narrow-to-region (point) 
4119                               (or (search-forward "\n\n" nil t) (point)))
4120             (delete-region (point-min) (point-max)))
4121         (when (and (not current-prefix-arg)
4122                    message-forward-ignored-headers)
4123           (save-restriction
4124             (narrow-to-region b e)
4125             (goto-char b)
4126             (narrow-to-region (point) 
4127                               (or (search-forward "\n\n" nil t) (point)))
4128             (message-remove-header message-forward-ignored-headers t)))))
4129     (message-position-point)))
4130
4131 ;;;###autoload
4132 (defun message-resend (address)
4133   "Resend the current article to ADDRESS."
4134   (interactive
4135    (list (message-read-from-minibuffer "Resend message to: ")))
4136   (message "Resending message to %s..." address)
4137   (save-excursion
4138     (let ((cur (current-buffer))
4139           beg)
4140       ;; We first set up a normal mail buffer.
4141       (set-buffer (get-buffer-create " *message resend*"))
4142       (erase-buffer)
4143       (message-setup `((To . ,address)))
4144       ;; Insert our usual headers.
4145       (message-generate-headers '(From Date To))
4146       (message-narrow-to-headers)
4147       ;; Rename them all to "Resent-*".
4148       (while (re-search-forward "^[A-Za-z]" nil t)
4149         (forward-char -1)
4150         (insert "Resent-"))
4151       (widen)
4152       (forward-line)
4153       (delete-region (point) (point-max))
4154       (setq beg (point))
4155       ;; Insert the message to be resent.
4156       (insert-buffer-substring cur)
4157       (goto-char (point-min))
4158       (search-forward "\n\n")
4159       (forward-char -1)
4160       (save-restriction
4161         (narrow-to-region beg (point))
4162         (message-remove-header message-ignored-resent-headers t)
4163         (goto-char (point-max)))
4164       (insert mail-header-separator)
4165       ;; Rename all old ("Also-")Resent headers.
4166       (while (re-search-backward "^\\(Also-\\)*Resent-" beg t)
4167         (beginning-of-line)
4168         (insert "Also-"))
4169       ;; Quote any "From " lines at the beginning.
4170       (goto-char beg)
4171       (when (looking-at "From ")
4172         (replace-match "X-From-Line: "))
4173       ;; Send it.
4174       (let ((message-inhibit-body-encoding t)
4175             message-required-mail-headers)
4176         (message-send-mail))
4177       (kill-buffer (current-buffer)))
4178     (message "Resending message to %s...done" address)))
4179
4180 ;;;###autoload
4181 (defun message-bounce ()
4182   "Re-mail the current message.
4183 This only makes sense if the current message is a bounce message that
4184 contains some mail you have written which has been bounced back to
4185 you."
4186   (interactive)
4187   (let ((handles (mm-dissect-buffer t))
4188         boundary)
4189     (message-pop-to-buffer (message-buffer-name "bounce"))
4190     (if (stringp (car handles))
4191         ;; This is a MIME bounce.
4192         (mm-insert-part (car (last handles)))
4193       ;; This is a non-MIME bounce, so we try to remove things
4194       ;; manually.
4195       (mm-insert-part handles)
4196       (undo-boundary)
4197       (goto-char (point-min))
4198       (search-forward "\n\n" nil t)
4199       (or (and (re-search-forward message-unsent-separator nil t)
4200                (forward-line 1))
4201           (re-search-forward "^Return-Path:.*\n" nil t))
4202       ;; We remove everything before the bounced mail.
4203       (delete-region
4204        (point-min)
4205        (if (re-search-forward "^[^ \n\t]+:" nil t)
4206            (match-beginning 0)
4207          (point))))
4208     (mm-enable-multibyte)
4209     (mime-to-mml)
4210     (save-restriction
4211       (message-narrow-to-head)
4212       (message-remove-header message-ignored-bounced-headers t)
4213       (goto-char (point-max))
4214       (insert mail-header-separator))
4215     (message-position-point)))
4216
4217 ;;;
4218 ;;; Interactive entry points for new message buffers.
4219 ;;;
4220
4221 ;;;###autoload
4222 (defun message-mail-other-window (&optional to subject)
4223   "Like `message-mail' command, but display mail buffer in another window."
4224   (interactive)
4225   (let ((pop-up-windows t)
4226         (special-display-buffer-names nil)
4227         (special-display-regexps nil)
4228         (same-window-buffer-names nil)
4229         (same-window-regexps nil))
4230     (message-pop-to-buffer (message-buffer-name "mail" to)))
4231   (let ((message-this-is-mail t))
4232     (message-setup `((To . ,(or to "")) (Subject . ,(or subject ""))))))
4233
4234 ;;;###autoload
4235 (defun message-mail-other-frame (&optional to subject)
4236   "Like `message-mail' command, but display mail buffer in another frame."
4237   (interactive)
4238   (let ((pop-up-frames t)
4239         (special-display-buffer-names nil)
4240         (special-display-regexps nil)
4241         (same-window-buffer-names nil)
4242         (same-window-regexps nil))
4243     (message-pop-to-buffer (message-buffer-name "mail" to)))
4244   (let ((message-this-is-mail t))
4245     (message-setup `((To . ,(or to "")) (Subject . ,(or subject ""))))))
4246
4247 ;;;###autoload
4248 (defun message-news-other-window (&optional newsgroups subject)
4249   "Start editing a news article to be sent."
4250   (interactive)
4251   (let ((pop-up-windows t)
4252         (special-display-buffer-names nil)
4253         (special-display-regexps nil)
4254         (same-window-buffer-names nil)
4255         (same-window-regexps nil))
4256     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
4257   (let ((message-this-is-news t))
4258     (message-setup `((Newsgroups . ,(or newsgroups ""))
4259                      (Subject . ,(or subject ""))))))
4260
4261 ;;;###autoload
4262 (defun message-news-other-frame (&optional newsgroups subject)
4263   "Start editing a news article to be sent."
4264   (interactive)
4265   (let ((pop-up-frames t)
4266         (special-display-buffer-names nil)
4267         (special-display-regexps nil)
4268         (same-window-buffer-names nil)
4269         (same-window-regexps nil))
4270     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
4271   (let ((message-this-is-news t))
4272     (message-setup `((Newsgroups . ,(or newsgroups ""))
4273                      (Subject . ,(or subject ""))))))
4274
4275 ;;; underline.el
4276
4277 ;; This code should be moved to underline.el (from which it is stolen).
4278
4279 ;;;###autoload
4280 (defun bold-region (start end)
4281   "Bold all nonblank characters in the region.
4282 Works by overstriking characters.
4283 Called from program, takes two arguments START and END
4284 which specify the range to operate on."
4285   (interactive "r")
4286   (save-excursion
4287     (let ((end1 (make-marker)))
4288       (move-marker end1 (max start end))
4289       (goto-char (min start end))
4290       (while (< (point) end1)
4291         (or (looking-at "[_\^@- ]")
4292             (insert (char-after) "\b"))
4293         (forward-char 1)))))
4294
4295 ;;;###autoload
4296 (defun unbold-region (start end)
4297   "Remove all boldness (overstruck characters) in the region.
4298 Called from program, takes two arguments START and END
4299 which specify the range to operate on."
4300   (interactive "r")
4301   (save-excursion
4302     (let ((end1 (make-marker)))
4303       (move-marker end1 (max start end))
4304       (goto-char (min start end))
4305       (while (re-search-forward "\b" end1 t)
4306         (if (eq (char-after) (char-after (- (point) 2)))
4307             (delete-char -2))))))
4308
4309 (defalias 'message-exchange-point-and-mark 'exchange-point-and-mark)
4310
4311 ;; Support for toolbar
4312 (when (string-match "XEmacs\\|Lucid" emacs-version)
4313   (require 'messagexmas))
4314
4315 ;;; Group name completion.
4316
4317 (defvar message-newgroups-header-regexp
4318   "^\\(Newsgroups\\|Followup-To\\|Posted-To\\|Gcc\\):"
4319   "Regexp that match headers that lists groups.")
4320
4321 (defun message-tab ()
4322   "Expand group names in Newsgroups and Followup-To headers.
4323 Do a `tab-to-tab-stop' if not in those headers."
4324   (interactive)
4325   (if (let ((mail-abbrev-mode-regexp message-newgroups-header-regexp))
4326         (mail-abbrev-in-expansion-header-p))
4327       (message-expand-group)
4328     (tab-to-tab-stop)))
4329
4330 (defvar gnus-active-hashtb)
4331 (defun message-expand-group ()
4332   "Expand the group name under point."
4333   (let* ((b (save-excursion
4334               (save-restriction
4335                 (narrow-to-region
4336                  (save-excursion
4337                    (beginning-of-line)
4338                    (skip-chars-forward "^:")
4339                    (1+ (point)))
4340                  (point))
4341                 (skip-chars-backward "^, \t\n") (point))))
4342          (completion-ignore-case t)
4343          (string (buffer-substring b (progn (skip-chars-forward "^,\t\n ")
4344                                             (point))))
4345          (hashtb (and (boundp 'gnus-active-hashtb) gnus-active-hashtb))
4346          (completions (all-completions string hashtb))
4347          comp)
4348     (delete-region b (point))
4349     (cond
4350      ((= (length completions) 1)
4351       (if (string= (car completions) string)
4352           (progn
4353             (insert string)
4354             (message "Only matching group"))
4355         (insert (car completions))))
4356      ((and (setq comp (try-completion string hashtb))
4357            (not (string= comp string)))
4358       (insert comp))
4359      (t
4360       (insert string)
4361       (if (not comp)
4362           (message "No matching groups")
4363         (save-selected-window
4364           (pop-to-buffer "*Completions*")
4365           (buffer-disable-undo)
4366           (let ((buffer-read-only nil))
4367             (erase-buffer)
4368             (let ((standard-output (current-buffer)))
4369               (display-completion-list (sort completions 'string<)))
4370             (goto-char (point-min))
4371             (delete-region (point) (progn (forward-line 3) (point))))))))))
4372
4373 ;;; Help stuff.
4374
4375 (defun message-talkative-question (ask question show &rest text)
4376   "Call FUNCTION with argument QUESTION; optionally display TEXT... args.
4377 If SHOW is non-nil, the arguments TEXT... are displayed in a temp buffer.
4378 The following arguments may contain lists of values."
4379   (if (and show
4380            (setq text (message-flatten-list text)))
4381       (save-window-excursion
4382         (save-excursion
4383           (with-output-to-temp-buffer " *MESSAGE information message*"
4384             (set-buffer " *MESSAGE information message*")
4385             (fundamental-mode)          ; for Emacs 20.4+
4386             (mapcar 'princ text)
4387             (goto-char (point-min))))
4388         (funcall ask question))
4389     (funcall ask question)))
4390
4391 (defun message-flatten-list (list)
4392   "Return a new, flat list that contains all elements of LIST.
4393
4394 \(message-flatten-list '(1 (2 3 (4 5 (6))) 7))
4395 => (1 2 3 4 5 6 7)"
4396   (cond ((consp list)
4397          (apply 'append (mapcar 'message-flatten-list list)))
4398         (list
4399          (list list))))
4400
4401 (defun message-generate-new-buffer-clone-locals (name &optional varstr)
4402   "Create and return a buffer with a name based on NAME using generate-new-buffer.
4403 Then clone the local variables and values from the old buffer to the
4404 new one, cloning only the locals having a substring matching the
4405 regexp varstr."
4406   (let ((oldbuf (current-buffer)))
4407     (save-excursion
4408       (set-buffer (generate-new-buffer name))
4409       (message-clone-locals oldbuf varstr)
4410       (current-buffer))))
4411
4412 (defun message-clone-locals (buffer &optional varstr)
4413   "Clone the local variables from BUFFER to the current buffer."
4414   (let ((locals (save-excursion
4415                   (set-buffer buffer)
4416                   (buffer-local-variables)))
4417         (regexp "^gnus\\|^nn\\|^message\\|^user-mail-address"))
4418     (mapcar
4419      (lambda (local)
4420        (when (and (consp local)
4421                   (car local)
4422                   (string-match regexp (symbol-name (car local)))
4423                   (or (null varstr)
4424                       (string-match varstr (symbol-name (car local)))))
4425          (ignore-errors
4426            (set (make-local-variable (car local))
4427                 (cdr local)))))
4428      locals)))
4429
4430 ;;; Miscellaneous functions
4431
4432 ;; stolen (and renamed) from nnheader.el
4433 (if (fboundp 'subst-char-in-string)
4434     (defsubst message-replace-chars-in-string (string from to)
4435       (subst-char-in-string from to string))
4436   (defun message-replace-chars-in-string (string from to)
4437     "Replace characters in STRING from FROM to TO."
4438     (let ((string (substring string 0)) ;Copy string.
4439           (len (length string))
4440           (idx 0))
4441       ;; Replace all occurrences of FROM with TO.
4442       (while (< idx len)
4443         (when (= (aref string idx) from)
4444           (aset string idx to))
4445         (setq idx (1+ idx)))
4446       string)))
4447
4448 ;;;
4449 ;;; MIME functions
4450 ;;;
4451
4452 (defvar message-inhibit-body-encoding nil)
4453
4454 (defun message-encode-message-body ()
4455   (unless message-inhibit-body-encoding 
4456     (let ((mail-parse-charset (or mail-parse-charset
4457                                   message-default-charset))
4458           (case-fold-search t)
4459           lines content-type-p)
4460       (message-goto-body)
4461       (save-restriction
4462         (narrow-to-region (point) (point-max))
4463         (let ((new (mml-generate-mime)))
4464           (when new
4465             (delete-region (point-min) (point-max))
4466             (insert new)
4467             (goto-char (point-min))
4468             (if (eq (aref new 0) ?\n)
4469                 (delete-char 1)
4470               (search-forward "\n\n")
4471               (setq lines (buffer-substring (point-min) (1- (point))))
4472               (delete-region (point-min) (point))))))
4473       (save-restriction
4474         (message-narrow-to-headers-or-head)
4475         (message-remove-header "Mime-Version")
4476         (goto-char (point-max))
4477         (insert "MIME-Version: 1.0\n")
4478         (when lines
4479           (insert lines))
4480         (setq content-type-p
4481               (re-search-backward "^Content-Type:" nil t)))
4482       (save-restriction
4483         (message-narrow-to-headers-or-head)
4484         (message-remove-first-header "Content-Type")
4485         (message-remove-first-header "Content-Transfer-Encoding"))
4486       ;; We always make sure that the message has a Content-Type header.
4487       ;; This is because some broken MTAs and MUAs get awfully confused
4488       ;; when confronted with a message with a MIME-Version header and
4489       ;; without a Content-Type header.  For instance, Solaris'
4490       ;; /usr/bin/mail.
4491       (unless content-type-p
4492         (goto-char (point-min))
4493         (re-search-forward "^MIME-Version:")
4494         (forward-line 1)
4495         (insert "Content-Type: text/plain; charset=us-ascii\n")))))
4496
4497 (defun message-read-from-minibuffer (prompt)
4498   "Read from the minibuffer while providing abbrev expansion."
4499   (if (fboundp 'mail-abbrevs-setup)
4500       (let ((mail-abbrev-mode-regexp "")
4501             (minibuffer-setup-hook 'mail-abbrevs-setup))
4502         (read-from-minibuffer prompt))
4503     (let ((minibuffer-setup-hook 'mail-abbrev-minibuffer-setup-hook))
4504       (read-string prompt))))
4505
4506 (provide 'message)
4507
4508 (run-hooks 'message-load-hook)
4509
4510 ;; Local Variables:
4511 ;; coding: iso-8859-1
4512 ;; End:
4513
4514 ;;; message.el ends here