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