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