2001-10-19 Per Abrahamsen <abraham@dina.kvl.dk>
[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 'gnus-group-name-decode "gnus-group")
1138   (autoload 'gnus-groups-from-server "gnus")
1139   (autoload 'rmail-output "rmailout"))
1140
1141 \f
1142
1143 ;;;
1144 ;;; Utility functions.
1145 ;;;
1146
1147 (defmacro message-y-or-n-p (question show &rest text)
1148   "Ask QUESTION, displaying remaining args in a temporary buffer if SHOW."
1149   `(message-talkative-question 'y-or-n-p ,question ,show ,@text))
1150
1151 (defmacro message-delete-line (&optional n)
1152   "Delete the current line (and the next N lines)."
1153   `(delete-region (progn (beginning-of-line) (point))
1154                   (progn (forward-line ,(or n 1)) (point))))
1155
1156 (defun message-unquote-tokens (elems)
1157   "Remove double quotes (\") from strings in list ELEMS."
1158   (mapcar (lambda (item)
1159             (while (string-match "^\\(.*\\)\"\\(.*\\)$" item)
1160               (setq item (concat (match-string 1 item)
1161                                  (match-string 2 item))))
1162             item)
1163           elems))
1164
1165 (defun message-tokenize-header (header &optional separator)
1166   "Split HEADER into a list of header elements.
1167 SEPARATOR is a string of characters to be used as separators.  \",\"
1168 is used by default."
1169   (if (not header)
1170       nil
1171     (let ((regexp (format "[%s]+" (or separator ",")))
1172           (beg 1)
1173           (first t)
1174           quoted elems paren)
1175       (save-excursion
1176         (message-set-work-buffer)
1177         (insert header)
1178         (goto-char (point-min))
1179         (while (not (eobp))
1180           (if first
1181               (setq first nil)
1182             (forward-char 1))
1183           (cond ((and (> (point) beg)
1184                       (or (eobp)
1185                           (and (looking-at regexp)
1186                                (not quoted)
1187                                (not paren))))
1188                  (push (buffer-substring beg (point)) elems)
1189                  (setq beg (match-end 0)))
1190                 ((eq (char-after) ?\")
1191                  (setq quoted (not quoted)))
1192                 ((and (eq (char-after) ?\()
1193                       (not quoted))
1194                  (setq paren t))
1195                 ((and (eq (char-after) ?\))
1196                       (not quoted))
1197                  (setq paren nil))))
1198         (nreverse elems)))))
1199
1200 (defun message-mail-file-mbox-p (file)
1201   "Say whether FILE looks like a Unix mbox file."
1202   (when (and (file-exists-p file)
1203              (file-readable-p file)
1204              (file-regular-p file))
1205     (with-temp-buffer
1206       (nnheader-insert-file-contents file)
1207       (goto-char (point-min))
1208       (looking-at message-unix-mail-delimiter))))
1209
1210 (defun message-fetch-field (header &optional not-all)
1211   "The same as `mail-fetch-field', only remove all newlines."
1212   (let* ((inhibit-point-motion-hooks t)
1213          (case-fold-search t)
1214          (value (mail-fetch-field header nil (not not-all))))
1215     (when value
1216       (while (string-match "\n[\t ]+" value)
1217         (setq value (replace-match " " t t value)))
1218       (set-text-properties 0 (length value) nil value)
1219       value)))
1220
1221 (defun message-narrow-to-field ()
1222   "Narrow the buffer to the header on the current line."
1223   (beginning-of-line)
1224   (narrow-to-region
1225    (point)
1226    (progn
1227      (forward-line 1)
1228      (if (re-search-forward "^[^ \n\t]" nil t)
1229          (progn
1230            (beginning-of-line)
1231            (point))
1232        (point-max))))
1233   (goto-char (point-min)))
1234
1235 (defun message-add-header (&rest headers)
1236   "Add the HEADERS to the message header, skipping those already present."
1237   (while headers
1238     (let (hclean)
1239       (unless (string-match "^\\([^:]+\\):[ \t]*[^ \t]" (car headers))
1240         (error "Invalid header `%s'" (car headers)))
1241       (setq hclean (match-string 1 (car headers)))
1242       (save-restriction
1243         (message-narrow-to-headers)
1244         (unless (re-search-forward (concat "^" (regexp-quote hclean) ":") nil t)
1245           (goto-char (point-max))
1246           (if (string-match "\n$" (car headers))
1247               (insert (car headers))
1248             (insert (car headers) ?\n)))))
1249     (setq headers (cdr headers))))
1250
1251
1252 (defun message-fetch-reply-field (header)
1253   "Fetch field HEADER from the message we're replying to."
1254   (when (and message-reply-buffer
1255              (buffer-name message-reply-buffer))
1256     (save-excursion
1257       (set-buffer message-reply-buffer)
1258       (message-fetch-field header))))
1259
1260 (defun message-set-work-buffer ()
1261   (if (get-buffer " *message work*")
1262       (progn
1263         (set-buffer " *message work*")
1264         (erase-buffer))
1265     (set-buffer (get-buffer-create " *message work*"))
1266     (kill-all-local-variables)
1267     (mm-enable-multibyte)))
1268
1269 (defun message-functionp (form)
1270   "Return non-nil if FORM is funcallable."
1271   (or (and (symbolp form) (fboundp form))
1272       (and (listp form) (eq (car form) 'lambda))
1273       (byte-code-function-p form)))
1274
1275 (defun message-strip-list-identifiers (subject)
1276   "Remove list identifiers in `gnus-list-identifiers' from string SUBJECT."
1277   (require 'gnus-sum)                   ; for gnus-list-identifiers
1278   (let ((regexp (if (stringp gnus-list-identifiers)
1279                     gnus-list-identifiers
1280                   (mapconcat 'identity gnus-list-identifiers " *\\|"))))
1281     (if (string-match (concat "\\(\\(\\(Re: +\\)?\\(" regexp
1282                               " *\\)\\)+\\(Re: +\\)?\\)") subject)
1283         (concat (substring subject 0 (match-beginning 1))
1284                 (or (match-string 3 subject)
1285                     (match-string 5 subject))
1286                 (substring subject
1287                            (match-end 1)))
1288       subject)))
1289
1290 (defun message-strip-subject-re (subject)
1291   "Remove \"Re:\" from subject lines in string SUBJECT."
1292   (if (string-match message-subject-re-regexp subject)
1293       (substring subject (match-end 0))
1294     subject))
1295
1296 (defun message-remove-header (header &optional is-regexp first reverse)
1297   "Remove HEADER in the narrowed buffer.
1298 If IS-REGEXP, HEADER is a regular expression.
1299 If FIRST, only remove the first instance of the header.
1300 Return the number of headers removed."
1301   (goto-char (point-min))
1302   (let ((regexp (if is-regexp header (concat "^" (regexp-quote header) ":")))
1303         (number 0)
1304         (case-fold-search t)
1305         last)
1306     (while (and (not (eobp))
1307                 (not last))
1308       (if (if reverse
1309               (not (looking-at regexp))
1310             (looking-at regexp))
1311           (progn
1312             (incf number)
1313             (when first
1314               (setq last t))
1315             (delete-region
1316              (point)
1317              ;; There might be a continuation header, so we have to search
1318              ;; until we find a new non-continuation line.
1319              (progn
1320                (forward-line 1)
1321                (if (re-search-forward "^[^ \t]" nil t)
1322                    (goto-char (match-beginning 0))
1323                  (point-max)))))
1324         (forward-line 1)
1325         (if (re-search-forward "^[^ \t]" nil t)
1326             (goto-char (match-beginning 0))
1327           (goto-char (point-max)))))
1328     number))
1329
1330 (defun message-remove-first-header (header)
1331   "Remove the first instance of HEADER if there is more than one."
1332   (let ((count 0)
1333         (regexp (concat "^" (regexp-quote header) ":")))
1334     (save-excursion
1335       (goto-char (point-min))
1336       (while (re-search-forward regexp nil t)
1337         (incf count)))
1338     (while (> count 1)
1339       (message-remove-header header nil t)
1340       (decf count))))
1341
1342 (defun message-narrow-to-headers ()
1343   "Narrow the buffer to the head of the message."
1344   (widen)
1345   (narrow-to-region
1346    (goto-char (point-min))
1347    (if (re-search-forward
1348         (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
1349        (match-beginning 0)
1350      (point-max)))
1351   (goto-char (point-min)))
1352
1353 (defun message-narrow-to-head-1 ()
1354   "Like `message-narrow-to-head'.  Don't widen."
1355   (narrow-to-region
1356    (goto-char (point-min))
1357    (if (search-forward "\n\n" nil 1)
1358        (1- (point))
1359      (point-max)))
1360   (goto-char (point-min)))
1361
1362 (defun message-narrow-to-head ()
1363   "Narrow the buffer to the head of the message.
1364 Point is left at the beginning of the narrowed-to region."
1365   (widen)
1366   (message-narrow-to-head-1))
1367
1368 (defun message-narrow-to-headers-or-head ()
1369   "Narrow the buffer to the head of the message."
1370   (widen)
1371   (narrow-to-region
1372    (goto-char (point-min))
1373    (cond
1374     ((re-search-forward
1375       (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
1376      (match-beginning 0))
1377     ((search-forward "\n\n" nil t)
1378      (1- (point)))
1379     (t
1380      (point-max))))
1381   (goto-char (point-min)))
1382
1383 (defun message-news-p ()
1384   "Say whether the current buffer contains a news message."
1385   (and (not message-this-is-mail)
1386        (or message-this-is-news
1387            (save-excursion
1388              (save-restriction
1389                (message-narrow-to-headers)
1390                (and (message-fetch-field "newsgroups")
1391                     (not (message-fetch-field "posted-to"))))))))
1392
1393 (defun message-mail-p ()
1394   "Say whether the current buffer contains a mail message."
1395   (and (not message-this-is-news)
1396        (or message-this-is-mail
1397            (save-excursion
1398              (save-restriction
1399                (message-narrow-to-headers)
1400                (or (message-fetch-field "to")
1401                    (message-fetch-field "cc")
1402                    (message-fetch-field "bcc")))))))
1403
1404 (defun message-next-header ()
1405   "Go to the beginning of the next header."
1406   (beginning-of-line)
1407   (or (eobp) (forward-char 1))
1408   (not (if (re-search-forward "^[^ \t]" nil t)
1409            (beginning-of-line)
1410          (goto-char (point-max)))))
1411
1412 (defun message-sort-headers-1 ()
1413   "Sort the buffer as headers using `message-rank' text props."
1414   (goto-char (point-min))
1415   (require 'sort)
1416   (sort-subr
1417    nil 'message-next-header
1418    (lambda ()
1419      (message-next-header)
1420      (unless (bobp)
1421        (forward-char -1)))
1422    (lambda ()
1423      (or (get-text-property (point) 'message-rank)
1424          10000))))
1425
1426 (defun message-sort-headers ()
1427   "Sort the headers of the current message according to `message-header-format-alist'."
1428   (interactive)
1429   (save-excursion
1430     (save-restriction
1431       (let ((max (1+ (length message-header-format-alist)))
1432             rank)
1433         (message-narrow-to-headers)
1434         (while (re-search-forward "^[^ \n]+:" nil t)
1435           (put-text-property
1436            (match-beginning 0) (1+ (match-beginning 0))
1437            'message-rank
1438            (if (setq rank (length (memq (assq (intern (buffer-substring
1439                                                        (match-beginning 0)
1440                                                        (1- (match-end 0))))
1441                                               message-header-format-alist)
1442                                         message-header-format-alist)))
1443                (- max rank)
1444              (1+ max)))))
1445       (message-sort-headers-1))))
1446
1447 \f
1448
1449 ;;;
1450 ;;; Message mode
1451 ;;;
1452
1453 ;;; Set up keymap.
1454
1455 (defvar message-mode-map nil)
1456
1457 (unless message-mode-map
1458   (setq message-mode-map (make-keymap))
1459   (set-keymap-parent message-mode-map text-mode-map)
1460   (define-key message-mode-map "\C-c?" 'describe-mode)
1461
1462   (define-key message-mode-map "\C-c\C-f\C-t" 'message-goto-to)
1463   (define-key message-mode-map "\C-c\C-f\C-b" 'message-goto-bcc)
1464   (define-key message-mode-map "\C-c\C-f\C-w" 'message-goto-fcc)
1465   (define-key message-mode-map "\C-c\C-f\C-c" 'message-goto-cc)
1466   (define-key message-mode-map "\C-c\C-f\C-s" 'message-goto-subject)
1467   (define-key message-mode-map "\C-c\C-f\C-r" 'message-goto-reply-to)
1468   (define-key message-mode-map "\C-c\C-f\C-n" 'message-goto-newsgroups)
1469   (define-key message-mode-map "\C-c\C-f\C-d" 'message-goto-distribution)
1470   (define-key message-mode-map "\C-c\C-f\C-f" 'message-goto-followup-to)
1471   (define-key message-mode-map "\C-c\C-f\C-k" 'message-goto-keywords)
1472   (define-key message-mode-map "\C-c\C-f\C-u" 'message-goto-summary)
1473   (define-key message-mode-map "\C-c\C-b" 'message-goto-body)
1474   (define-key message-mode-map "\C-c\C-i" 'message-goto-signature)
1475
1476   (define-key message-mode-map "\C-c\C-t" 'message-insert-to)
1477   (define-key message-mode-map "\C-c\C-n" 'message-insert-newsgroups)
1478
1479   (define-key message-mode-map "\C-c\C-y" 'message-yank-original)
1480   (define-key message-mode-map "\C-c\M-\C-y" 'message-yank-buffer)
1481   (define-key message-mode-map "\C-c\C-q" 'message-fill-yanked-message)
1482   (define-key message-mode-map "\C-c\C-w" 'message-insert-signature)
1483   (define-key message-mode-map "\C-c\M-h" 'message-insert-headers)
1484   (define-key message-mode-map "\C-c\C-r" 'message-caesar-buffer-body)
1485   (define-key message-mode-map "\C-c\C-o" 'message-sort-headers)
1486   (define-key message-mode-map "\C-c\M-r" 'message-rename-buffer)
1487
1488   (define-key message-mode-map "\C-c\C-c" 'message-send-and-exit)
1489   (define-key message-mode-map "\C-c\C-s" 'message-send)
1490   (define-key message-mode-map "\C-c\C-k" 'message-kill-buffer)
1491   (define-key message-mode-map "\C-c\C-d" 'message-dont-send)
1492   (define-key message-mode-map "\C-c\n" 'gnus-delay-article)
1493
1494   (define-key message-mode-map "\C-c\C-e" 'message-elide-region)
1495   (define-key message-mode-map "\C-c\C-v" 'message-delete-not-region)
1496   (define-key message-mode-map "\C-c\C-z" 'message-kill-to-signature)
1497   (define-key message-mode-map "\M-\r" 'message-newline-and-reformat)
1498   ;;(define-key message-mode-map "\M-q" 'message-fill-paragraph)
1499
1500   (define-key message-mode-map "\C-c\C-a" 'mml-attach-file)
1501
1502   (define-key message-mode-map "\t" 'message-tab)
1503   (define-key message-mode-map "\M-;" 'comment-region))
1504
1505 (easy-menu-define
1506   message-mode-menu message-mode-map "Message Menu."
1507   `("Message"
1508     ["Sort Headers" message-sort-headers t]
1509     ["Yank Original" message-yank-original t]
1510     ["Fill Yanked Message" message-fill-yanked-message t]
1511     ["Insert Signature" message-insert-signature t]
1512     ["Caesar (rot13) Message" message-caesar-buffer-body t]
1513     ["Caesar (rot13) Region" message-caesar-region (mark t)]
1514     ["Elide Region" message-elide-region (mark t)]
1515     ["Delete Outside Region" message-delete-not-region (mark t)]
1516     ["Kill To Signature" message-kill-to-signature t]
1517     ["Newline and Reformat" message-newline-and-reformat t]
1518     ["Rename buffer" message-rename-buffer t]
1519     ["Spellcheck" ispell-message
1520      ,@(if (featurep 'xemacs) '(t)
1521          '(:help "Spellcheck this message"))]
1522     "----"
1523     ["Send Message" message-send-and-exit
1524      ,@(if (featurep 'xemacs) '(t)
1525          '(:help "Send this message"))]
1526     ["Postpone Message" message-dont-send
1527      ,@(if (featurep 'xemacs) '(t)
1528          '(:help "File this draft message and exit"))]
1529     ["Send at Specific Time" gnus-delay-article
1530      ,@(if (featurep 'xemacs) '(t)
1531          '(:help "Ask, then arrange to send message at that time"))]
1532     ["Kill Message" message-kill-buffer
1533      ,@(if (featurep 'xemacs) '(t)
1534          '(:help "Delete this message without sending"))]))
1535
1536 (easy-menu-define
1537   message-mode-field-menu message-mode-map ""
1538   '("Field"
1539     ["Fetch To" message-insert-to t]
1540     ["Fetch Newsgroups" message-insert-newsgroups t]
1541     "----"
1542     ["To" message-goto-to t]
1543     ["Subject" message-goto-subject t]
1544     ["Cc" message-goto-cc t]
1545     ["Reply-To" message-goto-reply-to t]
1546     ["Summary" message-goto-summary t]
1547     ["Keywords" message-goto-keywords t]
1548     ["Newsgroups" message-goto-newsgroups t]
1549     ["Followup-To" message-goto-followup-to t]
1550     ["Distribution" message-goto-distribution t]
1551     ["Body" message-goto-body t]
1552     ["Signature" message-goto-signature t]))
1553
1554 (defvar message-tool-bar-map nil)
1555
1556 (eval-when-compile
1557   (defvar facemenu-add-face-function)
1558   (defvar facemenu-remove-face-function))
1559
1560 ;;;###autoload
1561 (define-derived-mode message-mode text-mode "Message"
1562   "Major mode for editing mail and news to be sent.
1563 Like Text Mode but with these additional commands:\\<message-mode-map>
1564 C-c C-s  `message-send' (send the message)  C-c C-c  `message-send-and-exit'
1565 C-c C-d  Postpone sending the message       C-c C-k  Kill the message
1566 C-c C-f  move to a header field (and create it if there isn't):
1567          C-c C-f C-t  move to To        C-c C-f C-s  move to Subject
1568          C-c C-f C-c  move to Cc        C-c C-f C-b  move to Bcc
1569          C-c C-f C-w  move to Fcc       C-c C-f C-r  move to Reply-To
1570          C-c C-f C-u  move to Summary   C-c C-f C-n  move to Newsgroups
1571          C-c C-f C-k  move to Keywords  C-c C-f C-d  move to Distribution
1572          C-c C-f C-f  move to Followup-To
1573 C-c C-t  `message-insert-to' (add a To header to a news followup)
1574 C-c C-n  `message-insert-newsgroups' (add a Newsgroup header to a news reply)
1575 C-c C-b  `message-goto-body' (move to beginning of message text).
1576 C-c C-i  `message-goto-signature' (move to the beginning of the signature).
1577 C-c C-w  `message-insert-signature' (insert `message-signature-file' file).
1578 C-c C-y  `message-yank-original' (insert current message, if any).
1579 C-c C-q  `message-fill-yanked-message' (fill what was yanked).
1580 C-c C-e  `message-elide-region' (elide the text between point and mark).
1581 C-c C-v  `message-delete-not-region' (remove the text outside the region).
1582 C-c C-z  `message-kill-to-signature' (kill the text up to the signature).
1583 C-c C-r  `message-caesar-buffer-body' (rot13 the message body).
1584 C-c C-a  `mml-attach-file' (attach a file as MIME).
1585 M-RET    `message-newline-and-reformat' (break the line and reformat)."
1586   (set (make-local-variable 'message-reply-buffer) nil)
1587   (make-local-variable 'message-send-actions)
1588   (make-local-variable 'message-exit-actions)
1589   (make-local-variable 'message-kill-actions)
1590   (make-local-variable 'message-postpone-actions)
1591   (make-local-variable 'message-draft-article)
1592   (setq buffer-offer-save t)
1593   (set (make-local-variable 'facemenu-add-face-function)
1594        (lambda (face end)
1595          (let ((face-fun (cdr (assq face message-face-alist))))
1596            (if face-fun
1597                (funcall face-fun (point) end)
1598              (error "Face %s not configured for %s mode" face mode-name)))
1599          ""))
1600   (set (make-local-variable 'facemenu-remove-face-function) t)
1601   (set (make-local-variable 'message-reply-headers) nil)
1602   (make-local-variable 'message-newsreader)
1603   (make-local-variable 'message-mailer)
1604   (make-local-variable 'message-post-method)
1605   (set (make-local-variable 'message-sent-message-via) nil)
1606   (set (make-local-variable 'message-checksum) nil)
1607   (set (make-local-variable 'message-mime-part) 0)
1608   (message-setup-fill-variables)
1609   ;; Allow using comment commands to add/remove quoting.
1610   (set (make-local-variable 'comment-start) message-yank-prefix)
1611   (if (featurep 'xemacs)
1612       (message-setup-toolbar)
1613     (set (make-local-variable 'font-lock-defaults)
1614          '(message-font-lock-keywords t))
1615     (if (boundp 'tool-bar-map)
1616         (set (make-local-variable 'tool-bar-map) (message-tool-bar-map))))
1617   (easy-menu-add message-mode-menu message-mode-map)
1618   (easy-menu-add message-mode-field-menu message-mode-map)
1619   ;; Allow mail alias things.
1620   (when (eq message-mail-alias-type 'abbrev)
1621     (if (fboundp 'mail-abbrevs-setup)
1622         (mail-abbrevs-setup)
1623       (mail-aliases-setup)))
1624   (message-set-auto-save-file-name)
1625   (mm-enable-multibyte)
1626   (set (make-local-variable 'indent-tabs-mode) nil) ;No tabs for indentation.
1627   (mml-mode))
1628
1629 (defun message-setup-fill-variables ()
1630   "Setup message fill variables."
1631   (set (make-local-variable 'fill-paragraph-function)
1632        'message-fill-paragraph)
1633   (make-local-variable 'paragraph-separate)
1634   (make-local-variable 'paragraph-start)
1635   (make-local-variable 'adaptive-fill-regexp)
1636   (unless (boundp 'adaptive-fill-first-line-regexp)
1637     (setq adaptive-fill-first-line-regexp nil))
1638   (make-local-variable 'adaptive-fill-first-line-regexp)
1639   (make-local-variable 'auto-fill-inhibit-regexp)
1640   (make-local-variable 'normal-auto-fill-function)
1641   (let ((quote-prefix-regexp
1642          ;; User should change message-cite-prefix-regexp if
1643          ;; message-yank-prefix is set to an abnormal value.
1644          (concat "\\(" message-cite-prefix-regexp "\\)[ \t]*")))
1645     (setq paragraph-start
1646           (concat
1647            (regexp-quote mail-header-separator) "$\\|"
1648            "[ \t]*$\\|"                 ; blank lines
1649            "-- $\\|"                    ; signature delimiter
1650            "---+$\\|"              ; delimiters for forwarded messages
1651            page-delimiter "$\\|"        ; spoiler warnings
1652            ".*wrote:$\\|"               ; attribution lines
1653            quote-prefix-regexp "$"))    ; empty lines in quoted text
1654     (setq paragraph-separate paragraph-start)
1655     (setq adaptive-fill-regexp
1656           (concat quote-prefix-regexp "\\|" adaptive-fill-regexp))
1657     (setq adaptive-fill-first-line-regexp
1658           (concat quote-prefix-regexp "\\|"
1659                   adaptive-fill-first-line-regexp))
1660     ;;(setq auto-fill-inhibit-regexp "^[A-Z][^: \n\t]+:")
1661     (setq auto-fill-inhibit-regexp nil)
1662     (setq normal-auto-fill-function 'message-do-auto-fill)))
1663
1664 \f
1665
1666 ;;;
1667 ;;; Message mode commands
1668 ;;;
1669
1670 ;;; Movement commands
1671
1672 (defun message-goto-to ()
1673   "Move point to the To header."
1674   (interactive)
1675   (message-position-on-field "To"))
1676
1677 (defun message-goto-subject ()
1678   "Move point to the Subject header."
1679   (interactive)
1680   (message-position-on-field "Subject"))
1681
1682 (defun message-goto-cc ()
1683   "Move point to the Cc header."
1684   (interactive)
1685   (message-position-on-field "Cc" "To"))
1686
1687 (defun message-goto-bcc ()
1688   "Move point to the Bcc  header."
1689   (interactive)
1690   (message-position-on-field "Bcc" "Cc" "To"))
1691
1692 (defun message-goto-fcc ()
1693   "Move point to the Fcc header."
1694   (interactive)
1695   (message-position-on-field "Fcc" "To" "Newsgroups"))
1696
1697 (defun message-goto-reply-to ()
1698   "Move point to the Reply-To header."
1699   (interactive)
1700   (message-position-on-field "Reply-To" "Subject"))
1701
1702 (defun message-goto-newsgroups ()
1703   "Move point to the Newsgroups header."
1704   (interactive)
1705   (message-position-on-field "Newsgroups"))
1706
1707 (defun message-goto-distribution ()
1708   "Move point to the Distribution header."
1709   (interactive)
1710   (message-position-on-field "Distribution"))
1711
1712 (defun message-goto-followup-to ()
1713   "Move point to the Followup-To header."
1714   (interactive)
1715   (message-position-on-field "Followup-To" "Newsgroups"))
1716
1717 (defun message-goto-keywords ()
1718   "Move point to the Keywords header."
1719   (interactive)
1720   (message-position-on-field "Keywords" "Subject"))
1721
1722 (defun message-goto-summary ()
1723   "Move point to the Summary header."
1724   (interactive)
1725   (message-position-on-field "Summary" "Subject"))
1726
1727 (defun message-goto-body (&optional interactivep)
1728   "Move point to the beginning of the message body."
1729   (interactive (list t))
1730   (when (and interactivep
1731              (looking-at "[ \t]*\n"))
1732     (expand-abbrev))
1733   (goto-char (point-min))
1734   (or (search-forward (concat "\n" mail-header-separator "\n") nil t)
1735       (search-forward-regexp "[^:]+:\\([^\n]\\|\n[ \t]\\)+\n\n" nil t)))
1736
1737 (defun message-goto-eoh ()
1738   "Move point to the end of the headers."
1739   (interactive)
1740   (message-goto-body)
1741   (forward-line -1))
1742
1743 (defun message-goto-signature ()
1744   "Move point to the beginning of the message signature.
1745 If there is no signature in the article, go to the end and
1746 return nil."
1747   (interactive)
1748   (goto-char (point-min))
1749   (if (re-search-forward message-signature-separator nil t)
1750       (forward-line 1)
1751     (goto-char (point-max))
1752     nil))
1753
1754 \f
1755
1756 (defun message-insert-to (&optional force)
1757   "Insert a To header that points to the author of the article being replied to.
1758 If the original author requested not to be sent mail, the function signals
1759 an error.
1760 With the prefix argument FORCE, insert the header anyway."
1761   (interactive "P")
1762   (let ((co (message-fetch-reply-field "mail-copies-to")))
1763     (when (and (null force)
1764                co
1765                (or (equal (downcase co) "never")
1766                    (equal (downcase co) "nobody")))
1767       (error "The user has requested not to have copies sent via mail")))
1768   (when (and (message-position-on-field "To")
1769              (mail-fetch-field "to")
1770              (not (string-match "\\` *\\'" (mail-fetch-field "to"))))
1771     (insert ", "))
1772   (insert (or (message-fetch-reply-field "mail-reply-to")
1773               (message-fetch-reply-field "reply-to")
1774               (message-fetch-reply-field "from") "")))
1775
1776 (defun message-widen-reply ()
1777   "Widen the reply to include maximum recipients."
1778   (interactive)
1779   (let ((follow-to
1780          (and message-reply-buffer
1781               (buffer-name message-reply-buffer)
1782               (save-excursion
1783                 (set-buffer message-reply-buffer)
1784                 (message-get-reply-headers t)))))
1785     (save-excursion
1786       (save-restriction
1787         (message-narrow-to-headers)
1788         (dolist (elem follow-to)
1789           (message-remove-header (symbol-name (car elem)))
1790           (goto-char (point-min))
1791           (insert (symbol-name (car elem)) ": "
1792                   (cdr elem) "\n"))))))
1793
1794 (defun message-insert-newsgroups ()
1795   "Insert the Newsgroups header from the article being replied to."
1796   (interactive)
1797   (when (and (message-position-on-field "Newsgroups")
1798              (mail-fetch-field "newsgroups")
1799              (not (string-match "\\` *\\'" (mail-fetch-field "newsgroups"))))
1800     (insert ","))
1801   (insert (or (message-fetch-reply-field "newsgroups") "")))
1802
1803 \f
1804
1805 ;;; Various commands
1806
1807 (defun message-delete-not-region (beg end)
1808   "Delete everything in the body of the current message outside of the region."
1809   (interactive "r")
1810   (let (citeprefix)
1811     (save-excursion
1812       (goto-char beg)
1813       ;; snarf citation prefix, if appropriate
1814       (unless (eq (point) (progn (beginning-of-line) (point)))
1815         (when (looking-at message-cite-prefix-regexp)
1816           (setq citeprefix (match-string 0))))
1817       (goto-char end)
1818       (delete-region (point) (if (not (message-goto-signature))
1819                                  (point)
1820                                (forward-line -2)
1821                                (point)))
1822       (insert "\n")
1823       (goto-char beg)
1824       (delete-region beg (progn (message-goto-body)
1825                                 (forward-line 2)
1826                                 (point)))
1827       (when citeprefix
1828         (insert citeprefix))))
1829   (when (message-goto-signature)
1830     (forward-line -2)))
1831
1832 (defun message-kill-to-signature ()
1833   "Deletes all text up to the signature."
1834   (interactive)
1835   (let ((point (point)))
1836     (message-goto-signature)
1837     (unless (eobp)
1838       (forward-line -2))
1839     (kill-region point (point))
1840     (unless (bolp)
1841       (insert "\n"))))
1842
1843 (defun message-newline-and-reformat (&optional arg not-break)
1844   "Insert four newlines, and then reformat if inside quoted text.
1845 Prefix arg means justify as well."
1846   (interactive (list (if current-prefix-arg 'full)))
1847   (let (quoted point beg end leading-space bolp)
1848     (setq point (point))
1849     (beginning-of-line)
1850     (setq beg (point))
1851     (setq bolp (= beg point))
1852     ;; Find first line of the paragraph.
1853     (if not-break
1854         (while (and (not (eobp))
1855                     (not (looking-at message-cite-prefix-regexp))
1856                     (looking-at paragraph-start))
1857           (forward-line 1)))
1858     ;; Find the prefix
1859     (when (looking-at message-cite-prefix-regexp)
1860       (setq quoted (match-string 0))
1861       (goto-char (match-end 0))
1862       (looking-at "[ \t]*")
1863       (setq leading-space (match-string 0)))
1864     (if (and quoted
1865              (not not-break)
1866              (not bolp)
1867              (< (- point beg) (length quoted)))
1868         ;; break inside the cite prefix.
1869         (setq quoted nil
1870               end nil))
1871     (if quoted
1872         (progn
1873           (forward-line 1)
1874           (while (and (not (eobp))
1875                       (not (looking-at paragraph-separate))
1876                       (looking-at message-cite-prefix-regexp)
1877                       (equal quoted (match-string 0)))
1878             (goto-char (match-end 0))
1879             (looking-at "[ \t]*")
1880             (if (> (length leading-space) (length (match-string 0)))
1881                 (setq leading-space (match-string 0)))
1882             (forward-line 1))
1883           (setq end (point))
1884           (goto-char beg)
1885           (while (and (if (bobp) nil (forward-line -1) t)
1886                       (not (looking-at paragraph-start))
1887                       (looking-at message-cite-prefix-regexp)
1888                       (equal quoted (match-string 0)))
1889             (setq beg (point))
1890             (goto-char (match-end 0))
1891             (looking-at "[ \t]*")
1892             (if (> (length leading-space) (length (match-string 0)))
1893                 (setq leading-space (match-string 0)))))
1894       (while (and (not (eobp))
1895                   (not (looking-at paragraph-separate))
1896                   (not (looking-at message-cite-prefix-regexp)))
1897         (forward-line 1))
1898       (setq end (point))
1899       (goto-char beg)
1900       (while (and (if (bobp) nil (forward-line -1) t)
1901                   (not (looking-at paragraph-start))
1902                   (not (looking-at message-cite-prefix-regexp)))
1903         (setq beg (point))))
1904     (goto-char point)
1905     (save-restriction
1906       (narrow-to-region beg end)
1907       (if not-break
1908           (setq point nil)
1909         (if bolp
1910             (insert "\n")
1911           (insert "\n\n"))
1912         (setq point (point))
1913         (insert "\n\n")
1914         (delete-region (point) (re-search-forward "[ \t]*"))
1915         (when (and quoted (not bolp))
1916           (insert quoted leading-space)))
1917       (if quoted
1918           (let* ((adaptive-fill-regexp
1919                   (regexp-quote (concat quoted leading-space)))
1920                  (adaptive-fill-first-line-regexp
1921                   adaptive-fill-regexp ))
1922             (fill-paragraph arg))
1923         (fill-paragraph arg))
1924       (if point (goto-char point)))))
1925
1926 (defun message-fill-paragraph (&optional arg)
1927   "Like `fill-paragraph'."
1928   (interactive (list (if current-prefix-arg 'full)))
1929   (if (and (boundp 'filladapt-mode) filladapt-mode)
1930       nil
1931     (message-newline-and-reformat arg t)
1932     t))
1933
1934 (defun message-do-auto-fill ()
1935   "Like `do-auto-fill', but don't fill in message header."
1936   (when (> (point) (save-excursion (rfc822-goto-eoh)))
1937     (do-auto-fill)))
1938
1939 (defun message-insert-signature (&optional force)
1940   "Insert a signature.  See documentation for variable `message-signature'."
1941   (interactive (list 0))
1942   (let* ((signature
1943           (cond
1944            ((and (null message-signature)
1945                  (eq force 0))
1946             (save-excursion
1947               (goto-char (point-max))
1948               (not (re-search-backward message-signature-separator nil t))))
1949            ((and (null message-signature)
1950                  force)
1951             t)
1952            ((message-functionp message-signature)
1953             (funcall message-signature))
1954            ((listp message-signature)
1955             (eval message-signature))
1956            (t message-signature)))
1957          (signature
1958           (cond ((stringp signature)
1959                  signature)
1960                 ((and (eq t signature)
1961                       message-signature-file
1962                       (file-exists-p message-signature-file))
1963                  signature))))
1964     (when signature
1965       (goto-char (point-max))
1966       ;; Insert the signature.
1967       (unless (bolp)
1968         (insert "\n"))
1969       (insert "\n-- \n")
1970       (if (eq signature t)
1971           (insert-file-contents message-signature-file)
1972         (insert signature))
1973       (goto-char (point-max))
1974       (or (bolp) (insert "\n")))))
1975
1976 (defun message-elide-region (b e)
1977   "Elide the text in the region.
1978 An ellipsis (from `message-elide-ellipsis') will be inserted where the
1979 text was killed."
1980   (interactive "r")
1981   (kill-region b e)
1982   (insert message-elide-ellipsis))
1983
1984 (defvar message-caesar-translation-table nil)
1985
1986 (defun message-caesar-region (b e &optional n)
1987   "Caesar rotate region B to E by N, default 13, for decrypting netnews."
1988   (interactive
1989    (list
1990     (min (point) (or (mark t) (point)))
1991     (max (point) (or (mark t) (point)))
1992     (when current-prefix-arg
1993       (prefix-numeric-value current-prefix-arg))))
1994
1995   (setq n (if (numberp n) (mod n 26) 13)) ;canonize N
1996   (unless (or (zerop n)                 ; no action needed for a rot of 0
1997               (= b e))                  ; no region to rotate
1998     ;; We build the table, if necessary.
1999     (when (or (not message-caesar-translation-table)
2000               (/= (aref message-caesar-translation-table ?a) (+ ?a n)))
2001       (setq message-caesar-translation-table
2002             (message-make-caesar-translation-table n)))
2003     (translate-region b e message-caesar-translation-table)))
2004
2005 (defun message-make-caesar-translation-table (n)
2006   "Create a rot table with offset N."
2007   (let ((i -1)
2008         (table (make-string 256 0)))
2009     (while (< (incf i) 256)
2010       (aset table i i))
2011     (concat
2012      (substring table 0 ?A)
2013      (substring table (+ ?A n) (+ ?A n (- 26 n)))
2014      (substring table ?A (+ ?A n))
2015      (substring table (+ ?A 26) ?a)
2016      (substring table (+ ?a n) (+ ?a n (- 26 n)))
2017      (substring table ?a (+ ?a n))
2018      (substring table (+ ?a 26) 255))))
2019
2020 (defun message-caesar-buffer-body (&optional rotnum)
2021   "Caesar rotate all letters in the current buffer by 13 places.
2022 Used to encode/decode possibly offensive messages (commonly in rec.humor).
2023 With prefix arg, specifies the number of places to rotate each letter forward.
2024 Mail and USENET news headers are not rotated."
2025   (interactive (if current-prefix-arg
2026                    (list (prefix-numeric-value current-prefix-arg))
2027                  (list nil)))
2028   (save-excursion
2029     (save-restriction
2030       (when (message-goto-body)
2031         (narrow-to-region (point) (point-max)))
2032       (message-caesar-region (point-min) (point-max) rotnum))))
2033
2034 (defun message-pipe-buffer-body (program)
2035   "Pipe the message body in the current buffer through PROGRAM."
2036   (save-excursion
2037     (save-restriction
2038       (when (message-goto-body)
2039         (narrow-to-region (point) (point-max)))
2040       (shell-command-on-region
2041        (point-min) (point-max) program nil t))))
2042
2043 (defun message-rename-buffer (&optional enter-string)
2044   "Rename the *message* buffer to \"*message* RECIPIENT\".
2045 If the function is run with a prefix, it will ask for a new buffer
2046 name, rather than giving an automatic name."
2047   (interactive "Pbuffer name: ")
2048   (save-excursion
2049     (save-restriction
2050       (goto-char (point-min))
2051       (narrow-to-region (point)
2052                         (search-forward mail-header-separator nil 'end))
2053       (let* ((mail-to (or
2054                        (if (message-news-p) (message-fetch-field "Newsgroups")
2055                          (message-fetch-field "To"))
2056                        ""))
2057              (mail-trimmed-to
2058               (if (string-match "," mail-to)
2059                   (concat (substring mail-to 0 (match-beginning 0)) ", ...")
2060                 mail-to))
2061              (name-default (concat "*message* " mail-trimmed-to))
2062              (name (if enter-string
2063                        (read-string "New buffer name: " name-default)
2064                      name-default)))
2065         (rename-buffer name t)))))
2066
2067 (defun message-fill-yanked-message (&optional justifyp)
2068   "Fill the paragraphs of a message yanked into this one.
2069 Numeric argument means justify as well."
2070   (interactive "P")
2071   (save-excursion
2072     (goto-char (point-min))
2073     (search-forward (concat "\n" mail-header-separator "\n") nil t)
2074     (let ((fill-prefix message-yank-prefix))
2075       (fill-individual-paragraphs (point) (point-max) justifyp))))
2076
2077 (defun message-indent-citation ()
2078   "Modify text just inserted from a message to be cited.
2079 The inserted text should be the region.
2080 When this function returns, the region is again around the modified text.
2081
2082 Normally, indent each nonblank line `message-indentation-spaces' spaces.
2083 However, if `message-yank-prefix' is non-nil, insert that prefix on each line."
2084   (let ((start (point)))
2085     ;; Remove unwanted headers.
2086     (when message-ignored-cited-headers
2087       (let (all-removed)
2088         (save-restriction
2089           (narrow-to-region
2090            (goto-char start)
2091            (if (search-forward "\n\n" nil t)
2092                (1- (point))
2093              (point)))
2094           (message-remove-header message-ignored-cited-headers t)
2095           (when (= (point-min) (point-max))
2096             (setq all-removed t))
2097           (goto-char (point-max)))
2098         (if all-removed
2099             (goto-char start)
2100           (forward-line 1))))
2101     ;; Delete blank lines at the start of the buffer.
2102     (while (and (point-min)
2103                 (eolp)
2104                 (not (eobp)))
2105       (message-delete-line))
2106     ;; Delete blank lines at the end of the buffer.
2107     (goto-char (point-max))
2108     (unless (eolp)
2109       (insert "\n"))
2110     (while (and (zerop (forward-line -1))
2111                 (looking-at "$"))
2112       (message-delete-line))
2113     ;; Do the indentation.
2114     (if (null message-yank-prefix)
2115         (indent-rigidly start (mark t) message-indentation-spaces)
2116       (save-excursion
2117         (goto-char start)
2118           (while (< (point) (mark t))
2119           (if (looking-at ">")
2120               (insert message-yank-cited-prefix)
2121             (insert message-yank-prefix))
2122           (forward-line 1))))
2123     (goto-char start)))
2124
2125 (defun message-yank-original (&optional arg)
2126   "Insert the message being replied to, if any.
2127 Puts point before the text and mark after.
2128 Normally indents each nonblank line ARG spaces (default 3).  However,
2129 if `message-yank-prefix' is non-nil, insert that prefix on each line.
2130
2131 This function uses `message-cite-function' to do the actual citing.
2132
2133 Just \\[universal-argument] as argument means don't indent, insert no
2134 prefix, and don't delete any headers."
2135   (interactive "P")
2136   (let ((modified (buffer-modified-p)))
2137     (when (and message-reply-buffer
2138                message-cite-function)
2139       (delete-windows-on message-reply-buffer t)
2140       (insert-buffer message-reply-buffer)
2141       (unless arg
2142         (funcall message-cite-function))
2143       (message-exchange-point-and-mark)
2144       (unless (bolp)
2145         (insert ?\n))
2146       (unless modified
2147         (setq message-checksum (message-checksum))))))
2148
2149 (defun message-yank-buffer (buffer)
2150   "Insert BUFFER into the current buffer and quote it."
2151   (interactive "bYank buffer: ")
2152   (let ((message-reply-buffer buffer))
2153     (save-window-excursion
2154       (message-yank-original))))
2155
2156 (defun message-buffers ()
2157   "Return a list of active message buffers."
2158   (let (buffers)
2159     (save-excursion
2160       (dolist (buffer (buffer-list t))
2161         (set-buffer buffer)
2162         (when (and (eq major-mode 'message-mode)
2163                    (null message-sent-message-via))
2164           (push (buffer-name buffer) buffers))))
2165     (nreverse buffers)))
2166
2167 (defun message-cite-original-without-signature ()
2168   "Cite function in the standard Message manner."
2169   (let ((start (point))
2170         (end (mark t))
2171         (functions
2172          (when message-indent-citation-function
2173            (if (listp message-indent-citation-function)
2174                message-indent-citation-function
2175              (list message-indent-citation-function)))))
2176     (mml-quote-region start end)
2177     ;; Allow undoing.
2178     (undo-boundary)
2179     (goto-char end)
2180     (when (re-search-backward message-signature-separator start t)
2181       ;; Also peel off any blank lines before the signature.
2182       (forward-line -1)
2183       (while (looking-at "^[ \t]*$")
2184         (forward-line -1))
2185       (forward-line 1)
2186       (delete-region (point) end)
2187       (unless (search-backward "\n\n" start t)
2188         ;; Insert a blank line if it is peeled off.
2189         (insert "\n")))
2190     (goto-char start)
2191     (while functions
2192       (funcall (pop functions)))
2193     (when message-citation-line-function
2194       (unless (bolp)
2195         (insert "\n"))
2196       (funcall message-citation-line-function))))
2197
2198 (eval-when-compile (defvar mail-citation-hook)) ;Compiler directive
2199 (defun message-cite-original ()
2200   "Cite function in the standard Message manner."
2201   (if (and (boundp 'mail-citation-hook)
2202            mail-citation-hook)
2203       (run-hooks 'mail-citation-hook)
2204     (let ((start (point))
2205           (end (mark t))
2206           (functions
2207            (when message-indent-citation-function
2208              (if (listp message-indent-citation-function)
2209                  message-indent-citation-function
2210                (list message-indent-citation-function)))))
2211       (mml-quote-region start end)
2212       (goto-char start)
2213       (while functions
2214         (funcall (pop functions)))
2215       (when message-citation-line-function
2216         (unless (bolp)
2217           (insert "\n"))
2218         (funcall message-citation-line-function)))))
2219
2220 (defun message-insert-citation-line ()
2221   "Insert a simple citation line."
2222   (when message-reply-headers
2223     (insert (mail-header-from message-reply-headers) " writes:\n\n")))
2224
2225 (defun message-position-on-field (header &rest afters)
2226   (let ((case-fold-search t))
2227     (save-restriction
2228       (narrow-to-region
2229        (goto-char (point-min))
2230        (progn
2231          (re-search-forward
2232           (concat "^" (regexp-quote mail-header-separator) "$"))
2233          (match-beginning 0)))
2234       (goto-char (point-min))
2235       (if (re-search-forward (concat "^" (regexp-quote header) ":") nil t)
2236           (progn
2237             (re-search-forward "^[^ \t]" nil 'move)
2238             (beginning-of-line)
2239             (skip-chars-backward "\n")
2240             t)
2241         (while (and afters
2242                     (not (re-search-forward
2243                           (concat "^" (regexp-quote (car afters)) ":")
2244                           nil t)))
2245           (pop afters))
2246         (when afters
2247           (re-search-forward "^[^ \t]" nil 'move)
2248           (beginning-of-line))
2249         (insert header ": \n")
2250         (forward-char -1)
2251         nil))))
2252
2253 (defun message-remove-signature ()
2254   "Remove the signature from the text between point and mark.
2255 The text will also be indented the normal way."
2256   (save-excursion
2257     (let ((start (point))
2258           mark)
2259       (if (not (re-search-forward message-signature-separator (mark t) t))
2260           ;; No signature here, so we just indent the cited text.
2261           (message-indent-citation)
2262         ;; Find the last non-empty line.
2263         (forward-line -1)
2264         (while (looking-at "[ \t]*$")
2265           (forward-line -1))
2266         (forward-line 1)
2267         (setq mark (set-marker (make-marker) (point)))
2268         (goto-char start)
2269         (message-indent-citation)
2270         ;; Enable undoing the deletion.
2271         (undo-boundary)
2272         (delete-region mark (mark t))
2273         (set-marker mark nil)))))
2274
2275 \f
2276
2277 ;;;
2278 ;;; Sending messages
2279 ;;;
2280
2281 (defun message-send-and-exit (&optional arg)
2282   "Send message like `message-send', then, if no errors, exit from mail buffer."
2283   (interactive "P")
2284   (let ((buf (current-buffer))
2285         (actions message-exit-actions))
2286     (when (and (message-send arg)
2287                (buffer-name buf))
2288       (if message-kill-buffer-on-exit
2289           (kill-buffer buf)
2290         (bury-buffer buf)
2291         (when (eq buf (current-buffer))
2292           (message-bury buf)))
2293       (message-do-actions actions)
2294       t)))
2295
2296 (defun message-dont-send ()
2297   "Don't send the message you have been editing."
2298   (interactive)
2299   (set-buffer-modified-p t)
2300   (save-buffer)
2301   (let ((actions message-postpone-actions))
2302     (message-bury (current-buffer))
2303     (message-do-actions actions)))
2304
2305 (defun message-kill-buffer ()
2306   "Kill the current buffer."
2307   (interactive)
2308   (when (or (not (buffer-modified-p))
2309             (yes-or-no-p "Message modified; kill anyway? "))
2310     (let ((actions message-kill-actions))
2311       (setq buffer-file-name nil)
2312       (kill-buffer (current-buffer))
2313       (message-do-actions actions))))
2314
2315 (defun message-bury (buffer)
2316   "Bury this mail BUFFER."
2317   (let ((newbuf (other-buffer buffer)))
2318     (bury-buffer buffer)
2319     (if (and (fboundp 'frame-parameters)
2320              (cdr (assq 'dedicated (frame-parameters)))
2321              (not (null (delq (selected-frame) (visible-frame-list)))))
2322         (delete-frame (selected-frame))
2323       (switch-to-buffer newbuf))))
2324
2325 (defun message-send (&optional arg)
2326   "Send the message in the current buffer.
2327 If `message-interactive' is non-nil, wait for success indication or
2328 error messages, and inform user.
2329 Otherwise any failure is reported in a message back to the user from
2330 the mailer.
2331 The usage of ARG is defined by the instance that called Message.
2332 It should typically alter the sending method in some way or other."
2333   (interactive "P")
2334   ;; Make it possible to undo the coming changes.
2335   (undo-boundary)
2336   (let ((inhibit-read-only t))
2337     (put-text-property (point-min) (point-max) 'read-only nil))
2338   (message-fix-before-sending)
2339   (run-hooks 'message-send-hook)
2340   (message message-sending-message)
2341   (let ((alist message-send-method-alist)
2342         (success t)
2343         elem sent
2344         (message-options message-options))
2345     (message-options-set-recipient)
2346     (while (and success
2347                 (setq elem (pop alist)))
2348       (when (funcall (cadr elem))
2349         (when (and (or (not (memq (car elem)
2350                                   message-sent-message-via))
2351                        (if (or (message-gnksa-enable-p 'multiple-copies)
2352                                (not (eq (car elem) 'news)))
2353                            (y-or-n-p
2354                             (format
2355                              "Already sent message via %s; resend? "
2356                              (car elem)))
2357                          (error "Denied posting -- multiple copies")))
2358                    (setq success (funcall (caddr elem) arg)))
2359           (setq sent t))))
2360     (unless (or sent (not success))
2361       (error "No methods specified to send by"))
2362     (when (and success sent)
2363       (message-do-fcc)
2364       (save-excursion
2365         (run-hooks 'message-sent-hook))
2366       (message "Sending...done")
2367       ;; Mark the buffer as unmodified and delete auto-save.
2368       (set-buffer-modified-p nil)
2369       (delete-auto-save-file-if-necessary t)
2370       (message-disassociate-draft)
2371       ;; Delete other mail buffers and stuff.
2372       (message-do-send-housekeeping)
2373       (message-do-actions message-send-actions)
2374       ;; Return success.
2375       t)))
2376
2377 (defun message-send-via-mail (arg)
2378   "Send the current message via mail."
2379   (message-send-mail arg))
2380
2381 (defun message-send-via-news (arg)
2382   "Send the current message via news."
2383   (funcall message-send-news-function arg))
2384
2385 (defmacro message-check (type &rest forms)
2386   "Eval FORMS if TYPE is to be checked."
2387   `(or (message-check-element ,type)
2388        (save-excursion
2389          ,@forms)))
2390
2391 (put 'message-check 'lisp-indent-function 1)
2392 (put 'message-check 'edebug-form-spec '(form body))
2393
2394 (defun message-fix-before-sending ()
2395   "Do various things to make the message nice before sending it."
2396   ;; Make sure there's a newline at the end of the message.
2397   (goto-char (point-max))
2398   (unless (bolp)
2399     (insert "\n"))
2400   ;; Delete all invisible text.
2401   (message-check 'invisible-text
2402     (when (text-property-any (point-min) (point-max) 'invisible t)
2403       (put-text-property (point-min) (point-max) 'invisible nil)
2404       (unless (yes-or-no-p
2405                "Invisible text found and made visible; continue posting? ")
2406         (error "Invisible text found and made visible")))))
2407
2408 (defun message-add-action (action &rest types)
2409   "Add ACTION to be performed when doing an exit of type TYPES."
2410   (let (var)
2411     (while types
2412       (set (setq var (intern (format "message-%s-actions" (pop types))))
2413            (nconc (symbol-value var) (list action))))))
2414
2415 (defun message-do-actions (actions)
2416   "Perform all actions in ACTIONS."
2417   ;; Now perform actions on successful sending.
2418   (while actions
2419     (ignore-errors
2420       (cond
2421        ;; A simple function.
2422        ((message-functionp (car actions))
2423         (funcall (car actions)))
2424        ;; Something to be evaled.
2425        (t
2426         (eval (car actions)))))
2427     (pop actions)))
2428
2429 (defun message-send-mail-partially ()
2430   "Send mail as message/partial."
2431   ;; replace the header delimiter with a blank line
2432   (goto-char (point-min))
2433   (re-search-forward
2434    (concat "^" (regexp-quote mail-header-separator) "\n"))
2435   (replace-match "\n")
2436   (run-hooks 'message-send-mail-hook)
2437   (let ((p (goto-char (point-min)))
2438         (tembuf (message-generate-new-buffer-clone-locals " message temp"))
2439         (curbuf (current-buffer))
2440         (id (message-make-message-id)) (n 1)
2441         plist total  header required-mail-headers)
2442     (while (not (eobp))
2443       (if (< (point-max) (+ p message-send-mail-partially-limit))
2444           (goto-char (point-max))
2445         (goto-char (+ p message-send-mail-partially-limit))
2446         (beginning-of-line)
2447         (if (<= (point) p) (forward-line 1))) ;; In case of bad message.
2448       (push p plist)
2449       (setq p (point)))
2450     (setq total (length plist))
2451     (push (point-max) plist)
2452     (setq plist (nreverse plist))
2453     (unwind-protect
2454         (save-excursion
2455           (setq p (pop plist))
2456           (while plist
2457             (set-buffer curbuf)
2458             (copy-to-buffer tembuf p (car plist))
2459             (set-buffer tembuf)
2460             (goto-char (point-min))
2461             (if header
2462                 (progn
2463                   (goto-char (point-min))
2464                   (narrow-to-region (point) (point))
2465                   (insert header))
2466               (message-goto-eoh)
2467               (setq header (buffer-substring (point-min) (point)))
2468               (goto-char (point-min))
2469               (narrow-to-region (point) (point))
2470               (insert header)
2471               (message-remove-header "Mime-Version")
2472               (message-remove-header "Content-Type")
2473               (message-remove-header "Content-Transfer-Encoding")
2474               (message-remove-header "Message-ID")
2475               (message-remove-header "Lines")
2476               (goto-char (point-max))
2477               (insert "Mime-Version: 1.0\n")
2478               (setq header (buffer-substring (point-min) (point-max))))
2479             (goto-char (point-max))
2480             (insert (format "Content-Type: message/partial; id=\"%s\"; number=%d; total=%d\n\n"
2481                             id n total))
2482             (forward-char -1)
2483             (let ((mail-header-separator ""))
2484               (when (memq 'Message-ID message-required-mail-headers)
2485                 (insert "Message-ID: " (message-make-message-id) "\n"))
2486               (when (memq 'Lines message-required-mail-headers)
2487                 (insert "Lines: " (message-make-lines) "\n"))
2488               (message-goto-subject)
2489               (end-of-line)
2490               (insert (format " (%d/%d)" n total))
2491               (widen)
2492               (mm-with-unibyte-current-buffer
2493                 (funcall (or message-send-mail-real-function
2494                              message-send-mail-function))))
2495             (setq n (+ n 1))
2496             (setq p (pop plist))
2497             (erase-buffer)))
2498       (kill-buffer tembuf))))
2499
2500 (defun message-send-mail (&optional arg)
2501   (require 'mail-utils)
2502   (let* ((tembuf (message-generate-new-buffer-clone-locals " message temp"))
2503          (case-fold-search nil)
2504          (news (message-news-p))
2505          (mailbuf (current-buffer))
2506          (message-this-is-mail t)
2507          (message-posting-charset
2508           (if (fboundp 'gnus-setup-posting-charset)
2509               (gnus-setup-posting-charset nil)
2510             message-posting-charset)))
2511     (save-restriction
2512       (message-narrow-to-headers)
2513       ;; Insert some headers.
2514       (let ((message-deletable-headers
2515              (if news nil message-deletable-headers)))
2516         (message-generate-headers message-required-mail-headers))
2517       ;; Let the user do all of the above.
2518       (run-hooks 'message-header-hook))
2519     (unwind-protect
2520         (save-excursion
2521           (set-buffer tembuf)
2522           (erase-buffer)
2523           ;; Avoid copying text props.
2524           (insert (with-current-buffer mailbuf
2525                     (buffer-substring-no-properties (point-min) (point-max))))
2526           ;; Remove some headers.
2527           (message-encode-message-body)
2528           (save-restriction
2529             (message-narrow-to-headers)
2530             ;; We (re)generate the Lines header.
2531             (when (memq 'Lines message-required-mail-headers)
2532               (message-generate-headers '(Lines)))
2533             ;; Remove some headers.
2534             (message-remove-header message-ignored-mail-headers t)
2535             (let ((mail-parse-charset message-default-charset))
2536               (mail-encode-encoded-word-buffer)))
2537           (goto-char (point-max))
2538           ;; require one newline at the end.
2539           (or (= (preceding-char) ?\n)
2540               (insert ?\n))
2541           (when
2542               (save-restriction
2543                 (message-narrow-to-headers)
2544                 (and news
2545                      (or (message-fetch-field "cc")
2546                          (message-fetch-field "to"))
2547                      (let ((content-type (message-fetch-field "content-type")))
2548                        (or
2549                         (not content-type)
2550                         (string= "text/plain"
2551                                  (car
2552                                   (mail-header-parse-content-type
2553                                    content-type)))))))
2554             (message-insert-courtesy-copy))
2555           (if (or (not message-send-mail-partially-limit)
2556                   (< (point-max) message-send-mail-partially-limit)
2557                   (not (y-or-n-p "Message exceeds message-send-mail-partially-limit, send in parts? ")))
2558               (mm-with-unibyte-current-buffer
2559                 (message "Sending via mail...")
2560                 (funcall (or message-send-mail-real-function
2561                              message-send-mail-function)))
2562             (message-send-mail-partially)))
2563       (kill-buffer tembuf))
2564     (set-buffer mailbuf)
2565     (push 'mail message-sent-message-via)))
2566
2567 (defun message-send-mail-with-sendmail ()
2568   "Send off the prepared buffer with sendmail."
2569   (let ((errbuf (if message-interactive
2570                     (message-generate-new-buffer-clone-locals
2571                      " sendmail errors")
2572                   0))
2573         resend-to-addresses delimline)
2574     (let ((case-fold-search t))
2575       (save-restriction
2576         (message-narrow-to-headers)
2577         (setq resend-to-addresses (message-fetch-field "resent-to")))
2578       ;; Change header-delimiter to be what sendmail expects.
2579       (goto-char (point-min))
2580       (re-search-forward
2581        (concat "^" (regexp-quote mail-header-separator) "\n"))
2582       (replace-match "\n")
2583       (backward-char 1)
2584       (setq delimline (point-marker))
2585       (run-hooks 'message-send-mail-hook)
2586       ;; Insert an extra newline if we need it to work around
2587       ;; Sun's bug that swallows newlines.
2588       (goto-char (1+ delimline))
2589       (when (eval message-mailer-swallows-blank-line)
2590         (newline))
2591       (when message-interactive
2592         (save-excursion
2593           (set-buffer errbuf)
2594           (erase-buffer))))
2595     (let ((default-directory "/")
2596           (coding-system-for-write message-send-coding-system))
2597       (apply 'call-process-region
2598              (append (list (point-min) (point-max)
2599                            (if (boundp 'sendmail-program)
2600                                sendmail-program
2601                              "/usr/lib/sendmail")
2602                            nil errbuf nil "-oi")
2603                      ;; Always specify who from,
2604                      ;; since some systems have broken sendmails.
2605                      ;; But some systems are more broken with -f, so
2606                      ;; we'll let users override this.
2607                      (if (null message-sendmail-f-is-evil)
2608                          (list "-f" (message-make-address)))
2609                      ;; These mean "report errors by mail"
2610                      ;; and "deliver in background".
2611                      (if (null message-interactive) '("-oem" "-odb"))
2612                      ;; Get the addresses from the message
2613                      ;; unless this is a resend.
2614                      ;; We must not do that for a resend
2615                      ;; because we would find the original addresses.
2616                      ;; For a resend, include the specific addresses.
2617                      (if resend-to-addresses
2618                          (list resend-to-addresses)
2619                        '("-t")))))
2620     (when message-interactive
2621       (save-excursion
2622         (set-buffer errbuf)
2623         (goto-char (point-min))
2624         (while (re-search-forward "\n\n* *" nil t)
2625           (replace-match "; "))
2626         (if (not (zerop (buffer-size)))
2627             (error "Sending...failed to %s"
2628                    (buffer-substring (point-min) (point-max)))))
2629       (when (bufferp errbuf)
2630         (kill-buffer errbuf)))))
2631
2632 (defun message-send-mail-with-qmail ()
2633   "Pass the prepared message buffer to qmail-inject.
2634 Refer to the documentation for the variable `message-send-mail-function'
2635 to find out how to use this."
2636   ;; replace the header delimiter with a blank line
2637   (goto-char (point-min))
2638   (re-search-forward
2639    (concat "^" (regexp-quote mail-header-separator) "\n"))
2640   (replace-match "\n")
2641   (run-hooks 'message-send-mail-hook)
2642   ;; send the message
2643   (case
2644       (let ((coding-system-for-write message-send-coding-system))
2645         (apply
2646          'call-process-region 1 (point-max) message-qmail-inject-program
2647          nil nil nil
2648          ;; qmail-inject's default behaviour is to look for addresses on the
2649          ;; command line; if there're none, it scans the headers.
2650          ;; yes, it does The Right Thing w.r.t. Resent-To and it's kin.
2651          ;;
2652          ;; in general, ALL of qmail-inject's defaults are perfect for simply
2653          ;; reading a formatted (i. e., at least a To: or Resent-To header)
2654          ;; message from stdin.
2655          ;;
2656          ;; qmail also has the advantage of not having been raped by
2657          ;; various vendors, so we don't have to allow for that, either --
2658          ;; compare this with message-send-mail-with-sendmail and weep
2659          ;; for sendmail's lost innocence.
2660          ;;
2661          ;; all this is way cool coz it lets us keep the arguments entirely
2662          ;; free for -inject-arguments -- a big win for the user and for us
2663          ;; since we don't have to play that double-guessing game and the user
2664          ;; gets full control (no gestapo'ish -f's, for instance).  --sj
2665          message-qmail-inject-args))
2666     ;; qmail-inject doesn't say anything on it's stdout/stderr,
2667     ;; we have to look at the retval instead
2668     (0 nil)
2669     (100 (error "qmail-inject reported permanent failure"))
2670     (111 (error "qmail-inject reported transient failure"))
2671     ;; should never happen
2672     (t   (error "qmail-inject reported unknown failure"))))
2673
2674 (defun message-send-mail-with-mh ()
2675   "Send the prepared message buffer with mh."
2676   (let ((mh-previous-window-config nil)
2677         (name (mh-new-draft-name)))
2678     (setq buffer-file-name name)
2679     ;; MH wants to generate these headers itself.
2680     (when message-mh-deletable-headers
2681       (let ((headers message-mh-deletable-headers))
2682         (while headers
2683           (goto-char (point-min))
2684           (and (re-search-forward
2685                 (concat "^" (symbol-name (car headers)) ": *") nil t)
2686                (message-delete-line))
2687           (pop headers))))
2688     (run-hooks 'message-send-mail-hook)
2689     ;; Pass it on to mh.
2690     (mh-send-letter)))
2691
2692 (defun message-send-news (&optional arg)
2693   (let* ((tembuf (message-generate-new-buffer-clone-locals " *message temp*"))
2694          (case-fold-search nil)
2695          (method (if (message-functionp message-post-method)
2696                      (funcall message-post-method arg)
2697                    message-post-method))
2698          (newsgroups-field (save-restriction
2699                             (message-narrow-to-headers-or-head)
2700                             (message-fetch-field "Newsgroups")))
2701          (followup-field (save-restriction
2702                            (message-narrow-to-headers-or-head)
2703                            (message-fetch-field "Followup-To")))
2704          ;; BUG: We really need to get the charset for each name in the
2705          ;; Newsgroups and Followup-To lines to allow crossposting
2706          ;; between group namess with incompatible character sets.
2707          ;; -- Per Abrahamsen <abraham@dina.kvl.dk> 2001-10-08.
2708          (group-field-charset
2709           (gnus-group-name-charset method newsgroups-field))
2710          (followup-field-charset 
2711           (gnus-group-name-charset method (or followup-field "")))
2712          (rfc2047-header-encoding-alist
2713           (append (when group-field-charset
2714                     (list (cons "Newsgroups" group-field-charset)))
2715                   (when followup-field-charset
2716                     (list (cons "Followup-To" followup-field-charset)))
2717                   rfc2047-header-encoding-alist))
2718          (messbuf (current-buffer))
2719          (message-syntax-checks
2720           (if (and arg
2721                    (listp message-syntax-checks))
2722               (cons '(existing-newsgroups . disabled)
2723                     message-syntax-checks)
2724             message-syntax-checks))
2725          (message-this-is-news t)
2726          (message-posting-charset
2727           (gnus-setup-posting-charset newsgroups-field))
2728          result)
2729     (if (not (message-check-news-body-syntax))
2730         nil
2731       (save-restriction
2732         (message-narrow-to-headers)
2733         ;; Insert some headers.
2734         (message-generate-headers message-required-news-headers)
2735         ;; Let the user do all of the above.
2736         (run-hooks 'message-header-hook))
2737       ;; Note: This check will be disabled by the ".*" default value for
2738       ;; gnus-group-name-charset-group-alist. -- Pa 2001-10-07.
2739       (when (and group-field-charset
2740                  (listp message-syntax-checks))
2741         (setq message-syntax-checks
2742               (cons '(valid-newsgroups . disabled)
2743                     message-syntax-checks)))
2744       (message-cleanup-headers)
2745       (if (not (let ((message-post-method method))
2746                  (message-check-news-syntax)))
2747           nil
2748         (unwind-protect
2749             (save-excursion
2750               (set-buffer tembuf)
2751               (buffer-disable-undo)
2752               (erase-buffer)
2753               ;; Avoid copying text props.
2754               (insert (with-current-buffer messbuf
2755                         (buffer-substring-no-properties
2756                          (point-min) (point-max))))
2757               (message-encode-message-body)
2758               ;; Remove some headers.
2759               (save-restriction
2760                 (message-narrow-to-headers)
2761                 ;; We (re)generate the Lines header.
2762                 (when (memq 'Lines message-required-mail-headers)
2763                   (message-generate-headers '(Lines)))
2764                 ;; Remove some headers.
2765                 (message-remove-header message-ignored-news-headers t)
2766                 (let ((mail-parse-charset message-default-charset))
2767                   (mail-encode-encoded-word-buffer)))
2768               (goto-char (point-max))
2769               ;; require one newline at the end.
2770               (or (= (preceding-char) ?\n)
2771                   (insert ?\n))
2772               (let ((case-fold-search t))
2773                 ;; Remove the delimiter.
2774                 (goto-char (point-min))
2775                 (re-search-forward
2776                  (concat "^" (regexp-quote mail-header-separator) "\n"))
2777                 (replace-match "\n")
2778                 (backward-char 1))
2779               (run-hooks 'message-send-news-hook)
2780               (gnus-open-server method)
2781               (message "Sending news with %s..." (gnus-server-string method))
2782               (setq result (let ((mail-header-separator ""))
2783                              (gnus-request-post method))))
2784           (kill-buffer tembuf))
2785         (set-buffer messbuf)
2786         (if result
2787             (push 'news message-sent-message-via)
2788           (message "Couldn't send message via news: %s"
2789                    (nnheader-get-report (car method)))
2790           nil)))))
2791
2792 ;;;
2793 ;;; Header generation & syntax checking.
2794 ;;;
2795
2796 (defun message-check-element (type)
2797   "Return non-nil if this TYPE is not to be checked."
2798   (if (eq message-syntax-checks 'dont-check-for-anything-just-trust-me)
2799       t
2800     (let ((able (assq type message-syntax-checks)))
2801       (and (consp able)
2802            (eq (cdr able) 'disabled)))))
2803
2804 (defun message-check-news-syntax ()
2805   "Check the syntax of the message."
2806   (save-excursion
2807     (save-restriction
2808       (widen)
2809       ;; We narrow to the headers and check them first.
2810       (save-excursion
2811         (save-restriction
2812           (message-narrow-to-headers)
2813           (message-check-news-header-syntax))))))
2814
2815 (defun message-check-news-header-syntax ()
2816   (and
2817    ;; Check Newsgroups header.
2818    (message-check 'newsgroups
2819      (let ((group (message-fetch-field "newsgroups")))
2820        (or
2821         (and group
2822              (not (string-match "\\`[ \t]*\\'" group)))
2823         (ignore
2824          (message
2825           "The newsgroups field is empty or missing.  Posting is denied.")))))
2826    ;; Check the Subject header.
2827    (message-check 'subject
2828      (let* ((case-fold-search t)
2829             (subject (message-fetch-field "subject")))
2830        (or
2831         (and subject
2832              (not (string-match "\\`[ \t]*\\'" subject)))
2833         (ignore
2834          (message
2835           "The subject field is empty or missing.  Posting is denied.")))))
2836    ;; Check for commands in Subject.
2837    (message-check 'subject-cmsg
2838      (if (string-match "^cmsg " (message-fetch-field "subject"))
2839          (y-or-n-p
2840           "The control code \"cmsg\" is in the subject.  Really post? ")
2841        t))
2842    ;; Check for multiple identical headers.
2843    (message-check 'multiple-headers
2844      (let (found)
2845        (while (and (not found)
2846                    (re-search-forward "^[^ \t:]+: " nil t))
2847          (save-excursion
2848            (or (re-search-forward
2849                 (concat "^"
2850                         (regexp-quote
2851                          (setq found
2852                                (buffer-substring
2853                                 (match-beginning 0) (- (match-end 0) 2))))
2854                         ":")
2855                 nil t)
2856                (setq found nil))))
2857        (if found
2858            (y-or-n-p (format "Multiple %s headers.  Really post? " found))
2859          t)))
2860    ;; Check for Version and Sendsys.
2861    (message-check 'sendsys
2862      (if (re-search-forward "^Sendsys:\\|^Version:" nil t)
2863          (y-or-n-p
2864           (format "The article contains a %s command.  Really post? "
2865                   (buffer-substring (match-beginning 0)
2866                                     (1- (match-end 0)))))
2867        t))
2868    ;; See whether we can shorten Followup-To.
2869    (message-check 'shorten-followup-to
2870      (let ((newsgroups (message-fetch-field "newsgroups"))
2871            (followup-to (message-fetch-field "followup-to"))
2872            to)
2873        (when (and newsgroups
2874                   (string-match "," newsgroups)
2875                   (not followup-to)
2876                   (not
2877                    (zerop
2878                     (length
2879                      (setq to (completing-read
2880                                "Followups to: (default all groups) "
2881                                (mapcar (lambda (g) (list g))
2882                                        (cons "poster"
2883                                              (message-tokenize-header
2884                                               newsgroups)))))))))
2885          (goto-char (point-min))
2886          (insert "Followup-To: " to "\n"))
2887        t))
2888    ;; Check "Shoot me".
2889    (message-check 'shoot
2890      (if (re-search-forward
2891           "Message-ID.*.i-did-not-set--mail-host-address--so-shoot-me" nil t)
2892          (y-or-n-p "You appear to have a misconfigured system.  Really post? ")
2893        t))
2894    ;; Check for Approved.
2895    (message-check 'approved
2896      (if (re-search-forward "^Approved:" nil t)
2897          (y-or-n-p "The article contains an Approved header.  Really post? ")
2898        t))
2899    ;; Check the Message-ID header.
2900    (message-check 'message-id
2901      (let* ((case-fold-search t)
2902             (message-id (message-fetch-field "message-id" t)))
2903        (or (not message-id)
2904            ;; Is there an @ in the ID?
2905            (and (string-match "@" message-id)
2906                 ;; Is there a dot in the ID?
2907                 (string-match "@[^.]*\\." message-id)
2908                 ;; Does the ID end with a dot?
2909                 (not (string-match "\\.>" message-id)))
2910            (y-or-n-p
2911             (format "The Message-ID looks strange: \"%s\".  Really post? "
2912                     message-id)))))
2913    ;; Check the Newsgroups & Followup-To headers.
2914    (message-check 'existing-newsgroups
2915      (let* ((case-fold-search t)
2916             (newsgroups (message-fetch-field "newsgroups"))
2917             (followup-to (message-fetch-field "followup-to"))
2918             (groups (message-tokenize-header
2919                      (if followup-to
2920                          (concat newsgroups "," followup-to)
2921                        newsgroups)))
2922             (post-method (if (message-functionp message-post-method)
2923                              (funcall message-post-method)
2924                            message-post-method))
2925             ;; KLUDGE to handle nnvirtual groups.  Doing this right
2926             ;; would probably involve a new nnoo function.
2927             ;; -- Per Abrahamsen <abraham@dina.kvl.dk>, 2001-10-17.
2928             (method (if (and (consp post-method) 
2929                              (eq (car post-method) 'nnvirtual)
2930                              gnus-message-group-art)
2931                         (let ((group (car (nnvirtual-find-group-art
2932                                            (car gnus-message-group-art)
2933                                            (cdr gnus-message-group-art)))))
2934                           (gnus-find-method-for-group group))
2935                       post-method))
2936             (known-groups
2937              (mapcar (lambda (n)
2938                        (gnus-group-name-decode 
2939                         (gnus-group-real-name n)
2940                         (gnus-group-name-charset method n)))
2941                      (gnus-groups-from-server method)))
2942             errors)
2943        (while groups
2944          (unless (or (equal (car groups) "poster")
2945                      (member (car groups) known-groups))
2946            (push (car groups) errors))
2947          (pop groups))
2948        (cond
2949         ;; Gnus is not running.
2950         ((or (not (and (boundp 'gnus-active-hashtb)
2951                        gnus-active-hashtb))
2952              (not (boundp 'gnus-read-active-file)))
2953          t)
2954         ;; We don't have all the group names.
2955         ((and (or (not gnus-read-active-file)
2956                   (eq gnus-read-active-file 'some))
2957               errors)
2958          (y-or-n-p
2959           (format
2960            "Really post to %s possibly unknown group%s: %s? "
2961            (if (= (length errors) 1) "this" "these")
2962            (if (= (length errors) 1) "" "s")
2963            (mapconcat 'identity errors ", "))))
2964         ;; There were no errors.
2965         ((not errors)
2966          t)
2967         ;; There are unknown groups.
2968         (t
2969          (y-or-n-p
2970           (format
2971            "Really post to %s unknown group%s: %s? "
2972            (if (= (length errors) 1) "this" "these")
2973            (if (= (length errors) 1) "" "s")
2974            (mapconcat 'identity errors ", ")))))))
2975    ;; Check the Newsgroups & Followup-To headers for syntax errors.
2976    (message-check 'valid-newsgroups
2977      (let ((case-fold-search t)
2978            (headers '("Newsgroups" "Followup-To"))
2979            header error)
2980        (while (and headers (not error))
2981          (when (setq header (mail-fetch-field (car headers)))
2982            (if (or
2983                 (not
2984                  (string-match
2985                   "\\`\\([-+_&.a-zA-Z0-9]+\\)?\\(,[-+_&.a-zA-Z0-9]+\\)*\\'"
2986                   header))
2987                 (memq
2988                  nil (mapcar
2989                       (lambda (g)
2990                         (not (string-match "\\.\\'\\|\\.\\." g)))
2991                       (message-tokenize-header header ","))))
2992                (setq error t)))
2993          (unless error
2994            (pop headers)))
2995        (if (not error)
2996            t
2997          (y-or-n-p
2998           (format "The %s header looks odd: \"%s\".  Really post? "
2999                   (car headers) header)))))
3000    (message-check 'repeated-newsgroups
3001      (let ((case-fold-search t)
3002            (headers '("Newsgroups" "Followup-To"))
3003            header error groups group)
3004        (while (and headers
3005                    (not error))
3006          (when (setq header (mail-fetch-field (pop headers)))
3007            (setq groups (message-tokenize-header header ","))
3008            (while (setq group (pop groups))
3009              (when (member group groups)
3010                (setq error group
3011                      groups nil)))))
3012        (if (not error)
3013            t
3014          (y-or-n-p
3015           (format "Group %s is repeated in headers.  Really post? " error)))))
3016    ;; Check the From header.
3017    (message-check 'from
3018      (let* ((case-fold-search t)
3019             (from (message-fetch-field "from"))
3020             ad)
3021        (cond
3022         ((not from)
3023          (message "There is no From line.  Posting is denied.")
3024          nil)
3025         ((or (not (string-match
3026                    "@[^\\.]*\\."
3027                    (setq ad (nth 1 (mail-extract-address-components
3028                                     from))))) ;larsi@ifi
3029              (string-match "\\.\\." ad) ;larsi@ifi..uio
3030              (string-match "@\\." ad)   ;larsi@.ifi.uio
3031              (string-match "\\.$" ad)   ;larsi@ifi.uio.
3032              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
3033              (string-match "(.*).*(.*)" from)) ;(lars) (lars)
3034          (message
3035           "Denied posting -- the From looks strange: \"%s\"." from)
3036          nil)
3037         ((let ((addresses (rfc822-addresses from)))
3038            (while (and addresses
3039                        (not (eq (string-to-char (car addresses)) ?\()))
3040              (setq addresses (cdr addresses)))
3041            addresses)
3042          (message
3043           "Denied posting -- bad From address: \"%s\"." from)
3044          nil)
3045         (t t))))
3046    ;; Check the Reply-To header.
3047    (message-check 'reply-to
3048      (let* ((case-fold-search t)
3049             (reply-to (message-fetch-field "reply-to"))
3050             ad)
3051        (cond
3052         ((not reply-to)
3053          t)
3054         ((string-match "," reply-to)
3055          (y-or-n-p
3056           (format "Multiple Reply-To addresses: \"%s\". Really post? "
3057                   reply-to)))
3058         ((or (not (string-match
3059                    "@[^\\.]*\\."
3060                    (setq ad (nth 1 (mail-extract-address-components
3061                                     reply-to))))) ;larsi@ifi
3062              (string-match "\\.\\." ad) ;larsi@ifi..uio
3063              (string-match "@\\." ad)   ;larsi@.ifi.uio
3064              (string-match "\\.$" ad)   ;larsi@ifi.uio.
3065              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
3066              (string-match "(.*).*(.*)" reply-to)) ;(lars) (lars)
3067          (y-or-n-p
3068           (format
3069            "The Reply-To looks strange: \"%s\". Really post? "
3070            reply-to)))
3071         (t t))))))
3072
3073 (defun message-check-news-body-syntax ()
3074   (and
3075    ;; Check for long lines.
3076    (message-check 'long-lines
3077      (goto-char (point-min))
3078      (re-search-forward
3079       (concat "^" (regexp-quote mail-header-separator) "$"))
3080      (forward-line 1)
3081      (while (and
3082              (or (looking-at
3083                   "<#\\(/\\)?\\(multipart\\|part\\|external\\|mml\\)")
3084                  (let ((p (point)))
3085                    (end-of-line)
3086                    (< (- (point) p) 80)))
3087              (zerop (forward-line 1))))
3088      (or (bolp)
3089          (eobp)
3090          (y-or-n-p
3091           "You have lines longer than 79 characters.  Really post? ")))
3092    ;; Check whether the article is empty.
3093    (message-check 'empty
3094      (goto-char (point-min))
3095      (re-search-forward
3096       (concat "^" (regexp-quote mail-header-separator) "$"))
3097      (forward-line 1)
3098      (let ((b (point)))
3099        (goto-char (point-max))
3100        (re-search-backward message-signature-separator nil t)
3101        (beginning-of-line)
3102        (or (re-search-backward "[^ \n\t]" b t)
3103            (if (message-gnksa-enable-p 'empty-article)
3104                (y-or-n-p "Empty article.  Really post? ")
3105              (message "Denied posting -- Empty article.")
3106              nil))))
3107    ;; Check for control characters.
3108    (message-check 'control-chars
3109      (if (re-search-forward "[\000-\007\013\015-\032\034-\037\200-\237]" nil t)
3110          (y-or-n-p
3111           "The article contains control characters.  Really post? ")
3112        t))
3113    ;; Check excessive size.
3114    (message-check 'size
3115      (if (> (buffer-size) 60000)
3116          (y-or-n-p
3117           (format "The article is %d octets long.  Really post? "
3118                   (buffer-size)))
3119        t))
3120    ;; Check whether any new text has been added.
3121    (message-check 'new-text
3122      (or
3123       (not message-checksum)
3124       (not (eq (message-checksum) message-checksum))
3125       (if (message-gnksa-enable-p 'quoted-text-only)
3126           (y-or-n-p
3127            "It looks like no new text has been added.  Really post? ")
3128         (message "Denied posting -- no new text has been added.")
3129         nil)))
3130    ;; Check the length of the signature.
3131    (message-check 'signature
3132      (goto-char (point-max))
3133      (if (> (count-lines (point) (point-max)) 5)
3134          (y-or-n-p
3135           (format
3136            "Your .sig is %d lines; it should be max 4.  Really post? "
3137            (1- (count-lines (point) (point-max)))))
3138        t))
3139    ;; Ensure that text follows last quoted portion.
3140    (message-check 'quoting-style
3141      (goto-char (point-max))
3142      (let ((no-problem t))
3143        (when (search-backward-regexp "^>[^\n]*\n" nil t)
3144          (setq no-problem (search-forward-regexp "^[ \t]*[^>\n]" nil t)))
3145        (if no-problem
3146            t
3147          (if (message-gnksa-enable-p 'quoted-text-only)
3148              (y-or-n-p "Your text should follow quoted text.  Really post? ")
3149            ;; Ensure that
3150            (goto-char (point-min))
3151            (re-search-forward
3152             (concat "^" (regexp-quote mail-header-separator) "$"))
3153            (if (search-forward-regexp "^[ \t]*[^>\n]" nil t)
3154                (y-or-n-p "Your text should follow quoted text.  Really post? ")
3155              (message "Denied posting -- only quoted text.")
3156              nil)))))))
3157
3158 (defun message-checksum ()
3159   "Return a \"checksum\" for the current buffer."
3160   (let ((sum 0))
3161     (save-excursion
3162       (goto-char (point-min))
3163       (re-search-forward
3164        (concat "^" (regexp-quote mail-header-separator) "$"))
3165       (while (not (eobp))
3166         (when (not (looking-at "[ \t\n]"))
3167           (setq sum (logxor (ash sum 1) (if (natnump sum) 0 1)
3168                             (char-after))))
3169         (forward-char 1)))
3170     sum))
3171
3172 (defun message-do-fcc ()
3173   "Process Fcc headers in the current buffer."
3174   (let ((case-fold-search t)
3175         (buf (current-buffer))
3176         list file)
3177     (save-excursion
3178       (save-restriction
3179         (message-narrow-to-headers)
3180         (setq file (message-fetch-field "fcc" t)))
3181       (when file
3182         (set-buffer (get-buffer-create " *message temp*"))
3183         (erase-buffer)
3184         (insert-buffer-substring buf)
3185         (message-encode-message-body)
3186         (save-restriction
3187           (message-narrow-to-headers)
3188           (while (setq file (message-fetch-field "fcc" t))
3189             (push file list)
3190             (message-remove-header "fcc" nil t))
3191           (let ((mail-parse-charset message-default-charset)
3192                 (rfc2047-header-encoding-alist
3193                  (cons '("Newsgroups" . default)
3194                        rfc2047-header-encoding-alist)))
3195             (mail-encode-encoded-word-buffer)))
3196         (goto-char (point-min))
3197         (when (re-search-forward
3198                (concat "^" (regexp-quote mail-header-separator) "$")
3199                nil t)
3200           (replace-match "" t t ))
3201         ;; Process FCC operations.
3202         (while list
3203           (setq file (pop list))
3204           (if (string-match "^[ \t]*|[ \t]*\\(.*\\)[ \t]*$" file)
3205               ;; Pipe the article to the program in question.
3206               (call-process-region (point-min) (point-max) shell-file-name
3207                                    nil nil nil shell-command-switch
3208                                    (match-string 1 file))
3209             ;; Save the article.
3210             (setq file (expand-file-name file))
3211             (unless (file-exists-p (file-name-directory file))
3212               (make-directory (file-name-directory file) t))
3213             (if (and message-fcc-handler-function
3214                      (not (eq message-fcc-handler-function 'rmail-output)))
3215                 (funcall message-fcc-handler-function file)
3216               (if (and (file-readable-p file) (mail-file-babyl-p file))
3217                   (rmail-output file 1 nil t)
3218                 (let ((mail-use-rfc822 t))
3219                   (rmail-output file 1 t t))))))
3220         (kill-buffer (current-buffer))))))
3221
3222 (defun message-output (filename)
3223   "Append this article to Unix/babyl mail file FILENAME."
3224   (if (and (file-readable-p filename)
3225            (mail-file-babyl-p filename))
3226       (gnus-output-to-rmail filename t)
3227     (gnus-output-to-mail filename t)))
3228
3229 (defun message-cleanup-headers ()
3230   "Do various automatic cleanups of the headers."
3231   ;; Remove empty lines in the header.
3232   (save-restriction
3233     (message-narrow-to-headers)
3234     ;; Remove blank lines.
3235     (while (re-search-forward "^[ \t]*\n" nil t)
3236       (replace-match "" t t))
3237
3238     ;; Correct Newsgroups and Followup-To headers:  Change sequence of
3239     ;; spaces to comma and eliminate spaces around commas.  Eliminate
3240     ;; embedded line breaks.
3241     (goto-char (point-min))
3242     (while (re-search-forward "^\\(Newsgroups\\|Followup-To\\): +" nil t)
3243       (save-restriction
3244         (narrow-to-region
3245          (point)
3246          (if (re-search-forward "^[^ \t]" nil t)
3247              (match-beginning 0)
3248            (forward-line 1)
3249            (point)))
3250         (goto-char (point-min))
3251         (while (re-search-forward "\n[ \t]+" nil t)
3252           (replace-match " " t t))     ;No line breaks (too confusing)
3253         (goto-char (point-min))
3254         (while (re-search-forward "[ \t\n]*,[ \t\n]*\\|[ \t]+" nil t)
3255           (replace-match "," t t))
3256         (goto-char (point-min))
3257         ;; Remove trailing commas.
3258         (when (re-search-forward ",+$" nil t)
3259           (replace-match "" t t))))))
3260
3261 (defun message-make-date (&optional now)
3262   "Make a valid data header.
3263 If NOW, use that time instead."
3264   (let* ((now (or now (current-time)))
3265          (zone (nth 8 (decode-time now)))
3266          (sign "+"))
3267     (when (< zone 0)
3268       (setq sign "-")
3269       (setq zone (- zone)))
3270     (concat
3271      ;; The day name of the %a spec is locale-specific.  Pfff.
3272      (format "%s, " (capitalize (car (rassoc (nth 6 (decode-time now))
3273                                              parse-time-weekdays))))
3274      (format-time-string "%d" now)
3275      ;; The month name of the %b spec is locale-specific.  Pfff.
3276      (format " %s "
3277              (capitalize (car (rassoc (nth 4 (decode-time now))
3278                                       parse-time-months))))
3279      (format-time-string "%Y %H:%M:%S " now)
3280      ;; We do all of this because XEmacs doesn't have the %z spec.
3281      (format "%s%02d%02d" sign (/ zone 3600) (/ (% zone 3600) 60)))))
3282
3283 (defun message-make-message-id ()
3284   "Make a unique Message-ID."
3285   (concat "<" (message-unique-id)
3286           (let ((psubject (save-excursion (message-fetch-field "subject")))
3287                 (psupersedes
3288                  (save-excursion (message-fetch-field "supersedes"))))
3289             (if (or
3290                  (and message-reply-headers
3291                       (mail-header-references message-reply-headers)
3292                       (mail-header-subject message-reply-headers)
3293                       psubject
3294                       (not (string=
3295                             (message-strip-subject-re
3296                              (mail-header-subject message-reply-headers))
3297                             (message-strip-subject-re psubject))))
3298                  (and psupersedes
3299                       (string-match "_-_@" psupersedes)))
3300                 "_-_" ""))
3301           "@" (message-make-fqdn) ">"))
3302
3303 (defvar message-unique-id-char nil)
3304
3305 ;; If you ever change this function, make sure the new version
3306 ;; cannot generate IDs that the old version could.
3307 ;; You might for example insert a "." somewhere (not next to another dot
3308 ;; or string boundary), or modify the "fsf" string.
3309 (defun message-unique-id ()
3310   ;; Don't use microseconds from (current-time), they may be unsupported.
3311   ;; Instead we use this randomly inited counter.
3312   (setq message-unique-id-char
3313         (% (1+ (or message-unique-id-char (logand (random t) (1- (lsh 1 20)))))
3314            ;; (current-time) returns 16-bit ints,
3315            ;; and 2^16*25 just fits into 4 digits i base 36.
3316            (* 25 25)))
3317   (let ((tm (current-time)))
3318     (concat
3319      (if (memq system-type '(ms-dos emx vax-vms))
3320          (let ((user (downcase (user-login-name))))
3321            (while (string-match "[^a-z0-9_]" user)
3322              (aset user (match-beginning 0) ?_))
3323            user)
3324        (message-number-base36 (user-uid) -1))
3325      (message-number-base36 (+ (car   tm)
3326                                (lsh (% message-unique-id-char 25) 16)) 4)
3327      (message-number-base36 (+ (nth 1 tm)
3328                                (lsh (/ message-unique-id-char 25) 16)) 4)
3329      ;; Append the newsreader name, because while the generated
3330      ;; ID is unique to this newsreader, other newsreaders might
3331      ;; otherwise generate the same ID via another algorithm.
3332      ".fsf")))
3333
3334 (defun message-number-base36 (num len)
3335   (if (if (< len 0)
3336           (<= num 0)
3337         (= len 0))
3338       ""
3339     (concat (message-number-base36 (/ num 36) (1- len))
3340             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
3341                                   (% num 36))))))
3342
3343 (defun message-make-organization ()
3344   "Make an Organization header."
3345   (let* ((organization
3346           (when message-user-organization
3347             (if (message-functionp message-user-organization)
3348                 (funcall message-user-organization)
3349               message-user-organization))))
3350     (save-excursion
3351       (message-set-work-buffer)
3352       (cond ((stringp organization)
3353              (insert organization))
3354             ((and (eq t organization)
3355                   message-user-organization-file
3356                   (file-exists-p message-user-organization-file))
3357              (insert-file-contents message-user-organization-file)))
3358       (goto-char (point-min))
3359       (while (re-search-forward "[\t\n]+" nil t)
3360         (replace-match "" t t))
3361       (unless (zerop (buffer-size))
3362         (buffer-string)))))
3363
3364 (defun message-make-lines ()
3365   "Count the number of lines and return numeric string."
3366   (save-excursion
3367     (save-restriction
3368       (widen)
3369       (message-goto-body)
3370       (int-to-string (count-lines (point) (point-max))))))
3371
3372 (defun message-make-in-reply-to ()
3373   "Return the In-Reply-To header for this message."
3374   (when message-reply-headers
3375     (let ((from (mail-header-from message-reply-headers))
3376           (date (mail-header-date message-reply-headers))
3377           (msg-id (mail-header-message-id message-reply-headers)))
3378       (when from
3379         (let ((stop-pos
3380                (string-match "  *at \\|  *@ \\| *(\\| *<" from)))
3381           (concat msg-id (if msg-id " (")
3382                   (if (and stop-pos
3383                            (not (zerop stop-pos)))
3384                       (substring from 0 stop-pos) from)
3385                   "'s message of \""
3386                   (if (or (not date) (string= date ""))
3387                       "(unknown date)" date)
3388                   "\"" (if msg-id ")")))))))
3389
3390 (defun message-make-distribution ()
3391   "Make a Distribution header."
3392   (let ((orig-distribution (message-fetch-reply-field "distribution")))
3393     (cond ((message-functionp message-distribution-function)
3394            (funcall message-distribution-function))
3395           (t orig-distribution))))
3396
3397 (defun message-make-expires ()
3398   "Return an Expires header based on `message-expires'."
3399   (let ((current (current-time))
3400         (future (* 1.0 message-expires 60 60 24)))
3401     ;; Add the future to current.
3402     (setcar current (+ (car current) (round (/ future (expt 2 16)))))
3403     (setcar (cdr current) (+ (nth 1 current) (% (round future) (expt 2 16))))
3404     (message-make-date current)))
3405
3406 (defun message-make-path ()
3407   "Return uucp path."
3408   (let ((login-name (user-login-name)))
3409     (cond ((null message-user-path)
3410            (concat (system-name) "!" login-name))
3411           ((stringp message-user-path)
3412            ;; Support GENERICPATH.  Suggested by vixie@decwrl.dec.com.
3413            (concat message-user-path "!" login-name))
3414           (t login-name))))
3415
3416 (defun message-make-from ()
3417   "Make a From header."
3418   (let* ((style message-from-style)
3419          (login (message-make-address))
3420          (fullname
3421           (or (and (boundp 'user-full-name)
3422                    user-full-name)
3423               (user-full-name))))
3424     (when (string= fullname "&")
3425       (setq fullname (user-login-name)))
3426     (save-excursion
3427       (message-set-work-buffer)
3428       (cond
3429        ((or (null style)
3430             (equal fullname ""))
3431         (insert login))
3432        ((or (eq style 'angles)
3433             (and (not (eq style 'parens))
3434                  ;; Use angles if no quoting is needed, or if parens would
3435                  ;; need quoting too.
3436                  (or (not (string-match "[^- !#-'*+/-9=?A-Z^-~]" fullname))
3437                      (let ((tmp (concat fullname nil)))
3438                        (while (string-match "([^()]*)" tmp)
3439                          (aset tmp (match-beginning 0) ?-)
3440                          (aset tmp (1- (match-end 0)) ?-))
3441                        (string-match "[\\()]" tmp)))))
3442         (insert fullname)
3443         (goto-char (point-min))
3444         ;; Look for a character that cannot appear unquoted
3445         ;; according to RFC 822.
3446         (when (re-search-forward "[^- !#-'*+/-9=?A-Z^-~]" nil 1)
3447           ;; Quote fullname, escaping specials.
3448           (goto-char (point-min))
3449           (insert "\"")
3450           (while (re-search-forward "[\"\\]" nil 1)
3451             (replace-match "\\\\\\&" t))
3452           (insert "\""))
3453         (insert " <" login ">"))
3454        (t                               ; 'parens or default
3455         (insert login " (")
3456         (let ((fullname-start (point)))
3457           (insert fullname)
3458           (goto-char fullname-start)
3459           ;; RFC 822 says \ and nonmatching parentheses
3460           ;; must be escaped in comments.
3461           ;; Escape every instance of ()\ ...
3462           (while (re-search-forward "[()\\]" nil 1)
3463             (replace-match "\\\\\\&" t))
3464           ;; ... then undo escaping of matching parentheses,
3465           ;; including matching nested parentheses.
3466           (goto-char fullname-start)
3467           (while (re-search-forward
3468                   "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
3469                   nil 1)
3470             (replace-match "\\1(\\3)" t)
3471             (goto-char fullname-start)))
3472         (insert ")")))
3473       (buffer-string))))
3474
3475 (defun message-make-sender ()
3476   "Return the \"real\" user address.
3477 This function tries to ignore all user modifications, and
3478 give as trustworthy answer as possible."
3479   (concat (user-login-name) "@" (system-name)))
3480
3481 (defun message-make-address ()
3482   "Make the address of the user."
3483   (or (message-user-mail-address)
3484       (concat (user-login-name) "@" (message-make-domain))))
3485
3486 (defun message-user-mail-address ()
3487   "Return the pertinent part of `user-mail-address'."
3488   (when user-mail-address
3489     (if (string-match " " user-mail-address)
3490         (nth 1 (mail-extract-address-components user-mail-address))
3491       user-mail-address)))
3492
3493 (defun message-make-fqdn ()
3494   "Return user's fully qualified domain name."
3495   (let ((system-name (system-name))
3496         (user-mail (message-user-mail-address)))
3497     (cond
3498      ((and (string-match "[^.]\\.[^.]" system-name)
3499            (not (string-match message-bogus-system-names system-name)))
3500       ;; `system-name' returned the right result.
3501       system-name)
3502      ;; Try `mail-host-address'.
3503      ((and (boundp 'mail-host-address)
3504            (stringp mail-host-address)
3505            (string-match "\\." mail-host-address))
3506       mail-host-address)
3507      ;; We try `user-mail-address' as a backup.
3508      ((and user-mail
3509            (string-match "\\." user-mail)
3510            (string-match "@\\(.*\\)\\'" user-mail))
3511       (match-string 1 user-mail))
3512      ;; Default to this bogus thing.
3513      (t
3514       (concat system-name ".i-did-not-set--mail-host-address--so-shoot-me")))))
3515
3516 (defun message-make-host-name ()
3517   "Return the name of the host."
3518   (let ((fqdn (message-make-fqdn)))
3519     (string-match "^[^.]+\\." fqdn)
3520     (substring fqdn 0 (1- (match-end 0)))))
3521
3522 (defun message-make-domain ()
3523   "Return the domain name."
3524   (or mail-host-address
3525       (message-make-fqdn)))
3526
3527 (defun message-generate-headers (headers)
3528   "Prepare article HEADERS.
3529 Headers already prepared in the buffer are not modified."
3530   (save-restriction
3531     (message-narrow-to-headers)
3532     (let* ((Date (message-make-date))
3533            (Message-ID (message-make-message-id))
3534            (Organization (message-make-organization))
3535            (From (message-make-from))
3536            (Path (message-make-path))
3537            (Subject nil)
3538            (Newsgroups nil)
3539            (In-Reply-To (message-make-in-reply-to))
3540            (To nil)
3541            (Distribution (message-make-distribution))
3542            (Lines (message-make-lines))
3543            (User-Agent message-newsreader)
3544            (Expires (message-make-expires))
3545            (case-fold-search t)
3546            header value elem)
3547       ;; First we remove any old generated headers.
3548       (let ((headers message-deletable-headers))
3549         (unless (buffer-modified-p)
3550           (setq headers (delq 'Message-ID (copy-sequence headers))))
3551         (while headers
3552           (goto-char (point-min))
3553           (and (re-search-forward
3554                 (concat "^" (symbol-name (car headers)) ": *") nil t)
3555                (get-text-property (1+ (match-beginning 0)) 'message-deletable)
3556                (message-delete-line))
3557           (pop headers)))
3558       ;; Go through all the required headers and see if they are in the
3559       ;; articles already.  If they are not, or are empty, they are
3560       ;; inserted automatically - except for Subject, Newsgroups and
3561       ;; Distribution.
3562       (while headers
3563         (goto-char (point-min))
3564         (setq elem (pop headers))
3565         (if (consp elem)
3566             (if (eq (car elem) 'optional)
3567                 (setq header (cdr elem))
3568               (setq header (car elem)))
3569           (setq header elem))
3570         (when (or (not (re-search-forward
3571                         (concat "^"
3572                                 (regexp-quote
3573                                  (downcase
3574                                   (if (stringp header)
3575                                       header
3576                                     (symbol-name header))))
3577                                 ":")
3578                         nil t))
3579                   (progn
3580                     ;; The header was found.  We insert a space after the
3581                     ;; colon, if there is none.
3582                     (if (/= (char-after) ? ) (insert " ") (forward-char 1))
3583                     ;; Find out whether the header is empty...
3584                     (looking-at "[ \t]*\n[^ \t]")))
3585           ;; So we find out what value we should insert.
3586           (setq value
3587                 (cond
3588                  ((and (consp elem) (eq (car elem) 'optional))
3589                   ;; This is an optional header.  If the cdr of this
3590                   ;; is something that is nil, then we do not insert
3591                   ;; this header.
3592                   (setq header (cdr elem))
3593                   (or (and (fboundp (cdr elem)) (funcall (cdr elem)))
3594                       (and (boundp (cdr elem)) (symbol-value (cdr elem)))))
3595                  ((consp elem)
3596                   ;; The element is a cons.  Either the cdr is a
3597                   ;; string to be inserted verbatim, or it is a
3598                   ;; function, and we insert the value returned from
3599                   ;; this function.
3600                   (or (and (stringp (cdr elem)) (cdr elem))
3601                       (and (fboundp (cdr elem)) (funcall (cdr elem)))))
3602                  ((and (boundp header) (symbol-value header))
3603                   ;; The element is a symbol.  We insert the value
3604                   ;; of this symbol, if any.
3605                   (symbol-value header))
3606                  ((not (message-check-element header))
3607                   ;; We couldn't generate a value for this header,
3608                   ;; so we just ask the user.
3609                   (read-from-minibuffer
3610                    (format "Empty header for %s; enter value: " header)))))
3611           ;; Finally insert the header.
3612           (when (and value
3613                      (not (equal value "")))
3614             (save-excursion
3615               (if (bolp)
3616                   (progn
3617                     ;; This header didn't exist, so we insert it.
3618                     (goto-char (point-max))
3619                     (insert (if (stringp header) header (symbol-name header))
3620                             ": " value "\n")
3621                     (forward-line -1))
3622                 ;; The value of this header was empty, so we clear
3623                 ;; totally and insert the new value.
3624                 (delete-region (point) (gnus-point-at-eol))
3625                 (insert value))
3626               ;; Add the deletable property to the headers that require it.
3627               (and (memq header message-deletable-headers)
3628                    (progn (beginning-of-line) (looking-at "[^:]+: "))
3629                    (add-text-properties
3630                     (point) (match-end 0)
3631                     '(message-deletable t face italic) (current-buffer)))))))
3632       ;; Insert new Sender if the From is strange.
3633       (let ((from (message-fetch-field "from"))
3634             (sender (message-fetch-field "sender"))
3635             (secure-sender (message-make-sender)))
3636         (when (and from
3637                    (not (message-check-element 'sender))
3638                    (not (string=
3639                          (downcase
3640                           (cadr (mail-extract-address-components from)))
3641                          (downcase secure-sender)))
3642                    (or (null sender)
3643                        (not
3644                         (string=
3645                          (downcase
3646                           (cadr (mail-extract-address-components sender)))
3647                          (downcase secure-sender)))))
3648           (goto-char (point-min))
3649           ;; Rename any old Sender headers to Original-Sender.
3650           (when (re-search-forward "^\\(Original-\\)*Sender:" nil t)
3651             (beginning-of-line)
3652             (insert "Original-")
3653             (beginning-of-line))
3654           (when (or (message-news-p)
3655                     (string-match "@.+\\.." secure-sender))
3656             (insert "Sender: " secure-sender "\n")))))))
3657
3658 (defun message-insert-courtesy-copy ()
3659   "Insert a courtesy message in mail copies of combined messages."
3660   (let (newsgroups)
3661     (save-excursion
3662       (save-restriction
3663         (message-narrow-to-headers)
3664         (when (setq newsgroups (message-fetch-field "newsgroups"))
3665           (goto-char (point-max))
3666           (insert "Posted-To: " newsgroups "\n")))
3667       (forward-line 1)
3668       (when message-courtesy-message
3669         (cond
3670          ((string-match "%s" message-courtesy-message)
3671           (insert (format message-courtesy-message newsgroups)))
3672          (t
3673           (insert message-courtesy-message)))))))
3674
3675 ;;;
3676 ;;; Setting up a message buffer
3677 ;;;
3678
3679 (defun message-fill-address (header value)
3680   (save-restriction
3681     (narrow-to-region (point) (point))
3682     (insert (capitalize (symbol-name header))
3683             ": "
3684             (if (consp value) (car value) value)
3685             "\n")
3686     (narrow-to-region (point-min) (1- (point-max)))
3687     (let (quoted last)
3688       (goto-char (point-min))
3689       (while (not (eobp))
3690         (skip-chars-forward "^,\"" (point-max))
3691         (if (or (eq (char-after) ?,)
3692                 (eobp))
3693             (when (not quoted)
3694               (if (and (> (current-column) 78)
3695                        last)
3696                   (progn
3697                     (save-excursion
3698                       (goto-char last)
3699                       (insert "\n\t"))
3700                     (setq last (1+ (point))))
3701                 (setq last (1+ (point)))))
3702           (setq quoted (not quoted)))
3703         (unless (eobp)
3704           (forward-char 1))))
3705     (goto-char (point-max))
3706     (widen)
3707     (forward-line 1)))
3708
3709 (defun message-fill-header (header value)
3710   (let ((begin (point))
3711         (fill-column 78)
3712         (fill-prefix "\t"))
3713     (insert (capitalize (symbol-name header))
3714             ": "
3715             (if (consp value) (car value) value)
3716             "\n")
3717     (save-restriction
3718       (narrow-to-region begin (point))
3719       (fill-region-as-paragraph begin (point))
3720       ;; Tapdance around looong Message-IDs.
3721       (forward-line -1)
3722       (when (looking-at "[ \t]*$")
3723         (message-delete-line))
3724       (goto-char begin)
3725       (re-search-forward ":" nil t)
3726       (when (looking-at "\n[ \t]+")
3727         (replace-match " " t t))
3728       (goto-char (point-max)))))
3729
3730 (defun message-shorten-1 (list cut surplus)
3731   "Cut SURPLUS elements out of LIST, beginning with CUTth one."
3732   (setcdr (nthcdr (- cut 2) list)
3733           (nthcdr (+ (- cut 2) surplus 1) list)))
3734
3735 (defun message-shorten-references (header references)
3736   "Trim REFERENCES to be 21 Message-ID long or less, and fold them.
3737 If folding is disallowed, also check that the REFERENCES are less
3738 than 988 characters long, and if they are not, trim them until they are."
3739   (let ((maxcount 21)
3740         (count 0)
3741         (cut 2)
3742         refs)
3743     (with-temp-buffer
3744       (insert references)
3745       (goto-char (point-min))
3746       ;; Cons a list of valid references.
3747       (while (re-search-forward "<[^>]+>" nil t)
3748         (push (match-string 0) refs))
3749       (setq refs (nreverse refs)
3750             count (length refs)))
3751
3752     ;; If the list has more than MAXCOUNT elements, trim it by
3753     ;; removing the CUTth element and the required number of
3754     ;; elements that follow.
3755     (when (> count maxcount)
3756       (let ((surplus (- count maxcount)))
3757         (message-shorten-1 refs cut surplus)
3758         (decf count surplus)))
3759
3760     ;; If folding is disallowed, make sure the total length (including
3761     ;; the spaces between) will be less than MAXSIZE characters.
3762     ;;
3763     ;; Only disallow folding for News messages. At this point the headers
3764     ;; have not been generated, thus we use message-this-is-news directly.
3765     (when (and message-this-is-news message-cater-to-broken-inn)
3766       (let ((maxsize 988)
3767             (totalsize (+ (apply #'+ (mapcar #'length refs))
3768                           (1- count)))
3769             (surplus 0)
3770             (ptr (nthcdr (1- cut) refs)))
3771         ;; Decide how many elements to cut off...
3772         (while (> totalsize maxsize)
3773           (decf totalsize (1+ (length (car ptr))))
3774           (incf surplus)
3775           (setq ptr (cdr ptr)))
3776         ;; ...and do it.
3777         (when (> surplus 0)
3778           (message-shorten-1 refs cut surplus))))
3779
3780     ;; Finally, collect the references back into a string and insert
3781     ;; it into the buffer.
3782     (let ((refstring (mapconcat #'identity refs " ")))
3783       (if (and message-this-is-news message-cater-to-broken-inn)
3784           (insert (capitalize (symbol-name header)) ": "
3785                   refstring "\n")
3786         (message-fill-header header refstring)))))
3787
3788 (defun message-position-point ()
3789   "Move point to where the user probably wants to find it."
3790   (message-narrow-to-headers)
3791   (cond
3792    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
3793     (search-backward ":" )
3794     (widen)
3795     (forward-char 1)
3796     (if (eq (char-after) ? )
3797         (forward-char 1)
3798       (insert " ")))
3799    (t
3800     (goto-char (point-max))
3801     (widen)
3802     (forward-line 1)
3803     (unless (looking-at "$")
3804       (forward-line 2)))
3805    (sit-for 0)))
3806
3807 (defun message-buffer-name (type &optional to group)
3808   "Return a new (unique) buffer name based on TYPE and TO."
3809   (cond
3810    ;; Generate a new buffer name The Message Way.
3811    ((eq message-generate-new-buffers 'unique)
3812     (generate-new-buffer-name
3813      (concat "*" type
3814              (if to
3815                  (concat " to "
3816                          (or (car (mail-extract-address-components to))
3817                              to) "")
3818                "")
3819              (if (and group (not (string= group ""))) (concat " on " group) "")
3820              "*")))
3821    ;; Check whether `message-generate-new-buffers' is a function,
3822    ;; and if so, call it.
3823    ((message-functionp message-generate-new-buffers)
3824     (funcall message-generate-new-buffers type to group))
3825    ((eq message-generate-new-buffers 'unsent)
3826     (generate-new-buffer-name
3827      (concat "*unsent " type
3828              (if to
3829                  (concat " to "
3830                          (or (car (mail-extract-address-components to))
3831                              to) "")
3832                "")
3833              (if (and group (not (string= group ""))) (concat " on " group) "")
3834              "*")))
3835    ;; Use standard name.
3836    (t
3837     (format "*%s message*" type))))
3838
3839 (defun message-pop-to-buffer (name)
3840   "Pop to buffer NAME, and warn if it already exists and is modified."
3841   (let ((buffer (get-buffer name)))
3842     (if (and buffer
3843              (buffer-name buffer))
3844         (progn
3845           (set-buffer (pop-to-buffer buffer))
3846           (when (and (buffer-modified-p)
3847                      (not (y-or-n-p
3848                            "Message already being composed; erase? ")))
3849             (error "Message being composed")))
3850       (set-buffer (pop-to-buffer name)))
3851     (erase-buffer)
3852     (message-mode)))
3853
3854 (defun message-do-send-housekeeping ()
3855   "Kill old message buffers."
3856   ;; We might have sent this buffer already.  Delete it from the
3857   ;; list of buffers.
3858   (setq message-buffer-list (delq (current-buffer) message-buffer-list))
3859   (while (and message-max-buffers
3860               message-buffer-list
3861               (>= (length message-buffer-list) message-max-buffers))
3862     ;; Kill the oldest buffer -- unless it has been changed.
3863     (let ((buffer (pop message-buffer-list)))
3864       (when (and (buffer-name buffer)
3865                  (not (buffer-modified-p buffer)))
3866         (kill-buffer buffer))))
3867   ;; Rename the buffer.
3868   (if message-send-rename-function
3869       (funcall message-send-rename-function)
3870     ;; Note: mail-abbrevs of XEmacs renames buffer name behind Gnus.
3871     (when (string-match
3872            "\\`\\*\\(sent \\|unsent \\)?\\(.+\\)\\*[^\\*]*\\|\\`mail to "
3873            (buffer-name))
3874       (let ((name (match-string 2 (buffer-name)))
3875             to group)
3876         (if (not (or (null name)
3877                      (string-equal name "mail")
3878                      (string-equal name "news")))
3879             (setq name (concat "*sent " name "*"))
3880           (message-narrow-to-headers)
3881           (setq to (message-fetch-field "to"))
3882           (setq group (message-fetch-field "newsgroups"))
3883           (widen)
3884           (setq name
3885                 (cond
3886                  (to (concat "*sent mail to "
3887                              (or (car (mail-extract-address-components to))
3888                                  to) "*"))
3889                  ((and group (not (string= group "")))
3890                   (concat "*sent news on " group "*"))
3891                  (t "*sent mail*"))))
3892         (unless (string-equal name (buffer-name))
3893           (rename-buffer name t)))))
3894   ;; Push the current buffer onto the list.
3895   (when message-max-buffers
3896     (setq message-buffer-list
3897           (nconc message-buffer-list (list (current-buffer))))))
3898
3899 (defun message-mail-user-agent ()
3900   (let ((mua (cond
3901               ((not message-mail-user-agent) nil)
3902               ((eq message-mail-user-agent t) mail-user-agent)
3903               (t message-mail-user-agent))))
3904     (if (memq mua '(message-user-agent gnus-user-agent))
3905         nil
3906       mua)))
3907
3908 (defun message-setup (headers &optional replybuffer actions switch-function)
3909   (let ((mua (message-mail-user-agent))
3910         subject to field yank-action)
3911     (if (not (and message-this-is-mail mua))
3912         (message-setup-1 headers replybuffer actions)
3913       (if replybuffer
3914           (setq yank-action (list 'insert-buffer replybuffer)))
3915       (setq headers (copy-sequence headers))
3916       (setq field (assq 'Subject headers))
3917       (when field
3918         (setq subject (cdr field))
3919         (setq headers (delq field headers)))
3920       (setq field (assq 'To headers))
3921       (when field
3922         (setq to (cdr field))
3923         (setq headers (delq field headers)))
3924       (let ((mail-user-agent mua))
3925         (compose-mail to subject
3926                       (mapcar (lambda (item)
3927                                 (cons
3928                                  (format "%s" (car item))
3929                                  (cdr item)))
3930                               headers)
3931                       nil switch-function yank-action actions)))))
3932
3933 ;;;(defvar mc-modes-alist)
3934 (defun message-setup-1 (headers &optional replybuffer actions)
3935 ;;;   (when (and (boundp 'mc-modes-alist)
3936 ;;;          (not (assq 'message-mode mc-modes-alist)))
3937 ;;;     (push '(message-mode (encrypt . mc-encrypt-message)
3938 ;;;                      (sign . mc-sign-message))
3939 ;;;       mc-modes-alist))
3940   (when actions
3941     (setq message-send-actions actions))
3942   (setq message-reply-buffer replybuffer)
3943   (goto-char (point-min))
3944   ;; Insert all the headers.
3945   (mail-header-format
3946    (let ((h headers)
3947          (alist message-header-format-alist))
3948      (while h
3949        (unless (assq (caar h) message-header-format-alist)
3950          (push (list (caar h)) alist))
3951        (pop h))
3952      alist)
3953    headers)
3954   (delete-region (point) (progn (forward-line -1) (point)))
3955   (when message-default-headers
3956     (insert message-default-headers)
3957     (or (bolp) (insert ?\n)))
3958   (put-text-property
3959    (point)
3960    (progn
3961      (insert mail-header-separator "\n")
3962      (1- (point)))
3963    'read-only nil)
3964   (forward-line -1)
3965   (when (message-news-p)
3966     (when message-default-news-headers
3967       (insert message-default-news-headers)
3968       (or (bolp) (insert ?\n)))
3969     (when message-generate-headers-first
3970       (message-generate-headers
3971        (delq 'Lines
3972              (delq 'Subject
3973                    (copy-sequence message-required-news-headers))))))
3974   (when (message-mail-p)
3975     (when message-default-mail-headers
3976       (insert message-default-mail-headers)
3977       (or (bolp) (insert ?\n)))
3978     (when message-generate-headers-first
3979       (message-generate-headers
3980        (delq 'Lines
3981              (delq 'Subject
3982                    (copy-sequence message-required-mail-headers))))))
3983   (run-hooks 'message-signature-setup-hook)
3984   (message-insert-signature)
3985   (save-restriction
3986     (message-narrow-to-headers)
3987     (if message-alternative-emails
3988         (message-use-alternative-email-as-from))
3989     (run-hooks 'message-header-setup-hook))
3990   (set-buffer-modified-p nil)
3991   (setq buffer-undo-list nil)
3992   (run-hooks 'message-setup-hook)
3993   (message-position-point)
3994   (undo-boundary))
3995
3996 (defun message-set-auto-save-file-name ()
3997   "Associate the message buffer with a file in the drafts directory."
3998   (when message-auto-save-directory
3999     (unless (file-directory-p
4000              (directory-file-name message-auto-save-directory))
4001       (gnus-make-directory message-auto-save-directory))
4002     (if (gnus-alive-p)
4003         (setq message-draft-article
4004               (nndraft-request-associate-buffer "drafts"))
4005       (setq buffer-file-name (expand-file-name
4006                               (if (memq system-type 
4007                                         '(ms-dos ms-windows windows-nt 
4008                                                  cygwin32 win32 w32 
4009                                                  mswindows))
4010                                   "message"
4011                                 "*message*")
4012                               message-auto-save-directory))
4013       (setq buffer-auto-save-file-name (make-auto-save-file-name)))
4014     (clear-visited-file-modtime)
4015     (setq buffer-file-coding-system message-draft-coding-system)))
4016
4017 (defun message-disassociate-draft ()
4018   "Disassociate the message buffer from the drafts directory."
4019   (when message-draft-article
4020     (nndraft-request-expire-articles
4021      (list message-draft-article) "drafts" nil t)))
4022
4023 (defun message-insert-headers ()
4024   "Generate the headers for the article."
4025   (interactive)
4026   (save-excursion
4027     (save-restriction
4028       (message-narrow-to-headers)
4029       (when (message-news-p)
4030         (message-generate-headers
4031          (delq 'Lines
4032                (delq 'Subject
4033                      (copy-sequence message-required-news-headers)))))
4034       (when (message-mail-p)
4035         (message-generate-headers
4036          (delq 'Lines
4037                (delq 'Subject
4038                      (copy-sequence message-required-mail-headers))))))))
4039
4040 \f
4041
4042 ;;;
4043 ;;; Commands for interfacing with message
4044 ;;;
4045
4046 ;;;###autoload
4047 (defun message-mail (&optional to subject
4048                                other-headers continue switch-function
4049                                yank-action send-actions)
4050   "Start editing a mail message to be sent.
4051 OTHER-HEADERS is an alist of header/value pairs."
4052   (interactive)
4053   (let ((message-this-is-mail t) replybuffer)
4054     (unless (message-mail-user-agent)
4055       (message-pop-to-buffer (message-buffer-name "mail" to)))
4056     ;; FIXME: message-mail should do something if YANK-ACTION is not
4057     ;; insert-buffer.
4058     (and (consp yank-action) (eq (car yank-action) 'insert-buffer)
4059          (setq replybuffer (nth 1 yank-action)))
4060     (message-setup
4061      (nconc
4062       `((To . ,(or to "")) (Subject . ,(or subject "")))
4063       (when other-headers other-headers))
4064      replybuffer send-actions)
4065     ;; FIXME: Should return nil if failure.
4066     t))
4067
4068 ;;;###autoload
4069 (defun message-news (&optional newsgroups subject)
4070   "Start editing a news article to be sent."
4071   (interactive)
4072   (let ((message-this-is-news t))
4073     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups))
4074     (message-setup `((Newsgroups . ,(or newsgroups ""))
4075                      (Subject . ,(or subject ""))))))
4076
4077 (defun message-get-reply-headers (wide &optional to-address)
4078   (let (follow-to mct never-mct from to cc reply-to mrt mft ccalist)
4079     ;; Find all relevant headers we need.
4080     (setq from (message-fetch-field "from")
4081           to (message-fetch-field "to")
4082           cc (message-fetch-field "cc")
4083           mct (message-fetch-field "mail-copies-to")
4084           reply-to (message-fetch-field "reply-to")
4085           mrt (message-fetch-field "mail-reply-to")
4086           mft (and message-use-mail-followup-to
4087                    (message-fetch-field "mail-followup-to")))
4088
4089     ;; Handle special values of Mail-Copies-To.
4090     (when mct
4091       (cond ((or (equal (downcase mct) "never")
4092                  (equal (downcase mct) "nobody"))
4093              (setq never-mct t)
4094              (setq mct nil))
4095             ((or (equal (downcase mct) "always")
4096                  (equal (downcase mct) "poster"))
4097              (setq mct (or mrt reply-to from)))))
4098
4099     (if (and (not mft)
4100              (or (not wide)
4101                  to-address))
4102         (progn
4103           (setq follow-to (list (cons 'To (or to-address mrt reply-to from))))
4104           (when (and (and wide mct)
4105                      (not (member (cons 'To mct) follow-to)))
4106             (push (cons 'Cc mct) follow-to)))
4107       (let (ccalist)
4108         (save-excursion
4109           (message-set-work-buffer)
4110           (if (and mft
4111                    wide
4112                    (or (not (eq message-use-mail-followup-to 'ask))
4113                        (message-y-or-n-p
4114                         (concat "Obey Mail-Followup-To? ") t "\
4115 You should normally obey the Mail-Followup-To: header.  In this
4116 article, it has the value of
4117
4118 " mft "
4119
4120 which directs your response to " (if (string-match "," mft)
4121                                      "the specified addresses"
4122                                    "that address only") ".
4123
4124 Most commonly, Mail-Followup-To is used by a mailing list poster to
4125 express that responses should be sent to just the list, and not the
4126 poster as well.
4127
4128 If a message is posted to several mailing lists, Mail-Followup-To may
4129 also be used to direct the following discussion to one list only,
4130 because discussions that are spread over several lists tend to be
4131 fragmented and very difficult to follow.
4132
4133 Also, some source/announcement lists are not intended for discussion;
4134 responses here are directed to other addresses.")))
4135               (insert mft)
4136             (unless never-mct
4137               (insert (or mrt reply-to from "")))
4138             (insert (if to (concat (if (bolp) "" ", ") to "") ""))
4139             (insert (if mct (concat (if (bolp) "" ", ") mct) ""))
4140             (insert (if cc (concat (if (bolp) "" ", ") cc) "")))
4141           (goto-char (point-min))
4142           (while (re-search-forward "[ \t]+" nil t)
4143             (replace-match " " t t))
4144           ;; Remove addresses that match `rmail-dont-reply-to-names'.
4145           (let ((rmail-dont-reply-to-names message-dont-reply-to-names))
4146             (insert (prog1 (rmail-dont-reply-to (buffer-string))
4147                       (erase-buffer))))
4148           (goto-char (point-min))
4149           ;; Perhaps "Mail-Copies-To: never" removed the only address?
4150           (when (eobp)
4151             (insert (or mrt reply-to from "")))
4152           (setq ccalist
4153                 (mapcar
4154                  (lambda (addr)
4155                    (cons (mail-strip-quoted-names addr) addr))
4156                  (message-tokenize-header (buffer-string))))
4157           (let ((s ccalist))
4158             (while s
4159               (setq ccalist (delq (assoc (car (pop s)) s) ccalist)))))
4160         (setq follow-to (list (cons 'To (cdr (pop ccalist)))))
4161         (when ccalist
4162           (let ((ccs (cons 'Cc (mapconcat
4163                                 (lambda (addr) (cdr addr)) ccalist ", "))))
4164             (when (string-match "^ +" (cdr ccs))
4165               (setcdr ccs (substring (cdr ccs) (match-end 0))))
4166             (push ccs follow-to)))
4167         ;; Allow the user to be asked whether or not to reply to all
4168         ;; recipients in a wide reply.
4169         (if (and ccalist wide message-wide-reply-confirm-recipients
4170                  (not (y-or-n-p "Reply to all recipients? ")))
4171             (setq follow-to (delq (assoc 'Cc follow-to) follow-to)))))
4172     follow-to))
4173
4174
4175 ;;;###autoload
4176 (defun message-reply (&optional to-address wide)
4177   "Start editing a reply to the article in the current buffer."
4178   (interactive)
4179   (require 'gnus-sum)                   ; for gnus-list-identifiers
4180   (let ((cur (current-buffer))
4181         from subject date reply-to to cc
4182         references message-id follow-to
4183         (inhibit-point-motion-hooks t)
4184         (message-this-is-mail t)
4185         gnus-warning)
4186     (save-restriction
4187       (message-narrow-to-head-1)
4188       ;; Allow customizations to have their say.
4189       (if (not wide)
4190           ;; This is a regular reply.
4191           (when (message-functionp message-reply-to-function)
4192             (save-excursion
4193               (setq follow-to (funcall message-reply-to-function))))
4194         ;; This is a followup.
4195         (when (message-functionp message-wide-reply-to-function)
4196           (save-excursion
4197             (setq follow-to
4198                   (funcall message-wide-reply-to-function)))))
4199       (setq message-id (message-fetch-field "message-id" t)
4200             references (message-fetch-field "references")
4201             date (message-fetch-field "date")
4202             from (message-fetch-field "from")
4203             subject (or (message-fetch-field "subject") "none"))
4204       (when gnus-list-identifiers
4205         (setq subject (message-strip-list-identifiers subject)))
4206       (setq subject (concat "Re: " (message-strip-subject-re subject)))
4207
4208       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
4209                  (string-match "<[^>]+>" gnus-warning))
4210         (setq message-id (match-string 0 gnus-warning)))
4211
4212       (unless follow-to
4213         (setq follow-to (message-get-reply-headers wide to-address))))
4214
4215     (unless (message-mail-user-agent)
4216       (message-pop-to-buffer
4217        (message-buffer-name
4218         (if wide "wide reply" "reply") from
4219         (if wide to-address nil))))
4220
4221     (setq message-reply-headers
4222           (vector 0 subject from date message-id references 0 0 ""))
4223
4224     (message-setup
4225      `((Subject . ,subject)
4226        ,@follow-to
4227        ,@(if (or references message-id)
4228              `((References . ,(concat (or references "") (and references " ")
4229                                       (or message-id ""))))
4230            nil))
4231      cur)))
4232
4233 ;;;###autoload
4234 (defun message-wide-reply (&optional to-address)
4235   "Make a \"wide\" reply to the message in the current buffer."
4236   (interactive)
4237   (message-reply to-address t))
4238
4239 ;;;###autoload
4240 (defun message-followup (&optional to-newsgroups)
4241   "Follow up to the message in the current buffer.
4242 If TO-NEWSGROUPS, use that as the new Newsgroups line."
4243   (interactive)
4244   (require 'gnus-sum)                   ; for gnus-list-identifiers
4245   (let ((cur (current-buffer))
4246         from subject date reply-to mrt mct
4247         references message-id follow-to
4248         (inhibit-point-motion-hooks t)
4249         (message-this-is-news t)
4250         followup-to distribution newsgroups gnus-warning posted-to)
4251     (save-restriction
4252       (narrow-to-region
4253        (goto-char (point-min))
4254        (if (search-forward "\n\n" nil t)
4255            (1- (point))
4256          (point-max)))
4257       (when (message-functionp message-followup-to-function)
4258         (setq follow-to
4259               (funcall message-followup-to-function)))
4260       (setq from (message-fetch-field "from")
4261             date (message-fetch-field "date")
4262             subject (or (message-fetch-field "subject") "none")
4263             references (message-fetch-field "references")
4264             message-id (message-fetch-field "message-id" t)
4265             followup-to (message-fetch-field "followup-to")
4266             newsgroups (message-fetch-field "newsgroups")
4267             posted-to (message-fetch-field "posted-to")
4268             reply-to (message-fetch-field "reply-to")
4269             mrt (message-fetch-field "mail-reply-to")
4270             distribution (message-fetch-field "distribution")
4271             mct (message-fetch-field "mail-copies-to"))
4272       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
4273                  (string-match "<[^>]+>" gnus-warning))
4274         (setq message-id (match-string 0 gnus-warning)))
4275       ;; Remove bogus distribution.
4276       (when (and (stringp distribution)
4277                  (let ((case-fold-search t))
4278                    (string-match "world" distribution)))
4279         (setq distribution nil))
4280       (if gnus-list-identifiers
4281           (setq subject (message-strip-list-identifiers subject)))
4282       (setq subject (concat "Re: " (message-strip-subject-re subject)))
4283       (widen))
4284
4285     (message-pop-to-buffer (message-buffer-name "followup" from newsgroups))
4286
4287     (message-setup
4288      `((Subject . ,subject)
4289        ,@(cond
4290           (to-newsgroups
4291            (list (cons 'Newsgroups to-newsgroups)))
4292           (follow-to follow-to)
4293           ((and followup-to message-use-followup-to)
4294            (list
4295             (cond
4296              ((equal (downcase followup-to) "poster")
4297               (if (or (eq message-use-followup-to 'use)
4298                       (message-y-or-n-p "Obey Followup-To: poster? " t "\
4299 You should normally obey the Followup-To: header.
4300
4301 `Followup-To: poster' sends your response via e-mail instead of news.
4302
4303 A typical situation where `Followup-To: poster' is used is when the poster
4304 does not read the newsgroup, so he wouldn't see any replies sent to it."))
4305                   (progn
4306                     (setq message-this-is-news nil)
4307                     (cons 'To (or mrt reply-to from "")))
4308                 (cons 'Newsgroups newsgroups)))
4309              (t
4310               (if (or (equal followup-to newsgroups)
4311                       (not (eq message-use-followup-to 'ask))
4312                       (message-y-or-n-p
4313                        (concat "Obey Followup-To: " followup-to "? ") t "\
4314 You should normally obey the Followup-To: header.
4315
4316         `Followup-To: " followup-to "'
4317 directs your response to " (if (string-match "," followup-to)
4318                                "the specified newsgroups"
4319                              "that newsgroup only") ".
4320
4321 If a message is posted to several newsgroups, Followup-To is often
4322 used to direct the following discussion to one newsgroup only,
4323 because discussions that are spread over several newsgroup tend to
4324 be fragmented and very difficult to follow.
4325
4326 Also, some source/announcement newsgroups are not intended for discussion;
4327 responses here are directed to other newsgroups."))
4328                   (cons 'Newsgroups followup-to)
4329                 (cons 'Newsgroups newsgroups))))))
4330           (posted-to
4331            `((Newsgroups . ,posted-to)))
4332           (t
4333            `((Newsgroups . ,newsgroups))))
4334        ,@(and distribution (list (cons 'Distribution distribution)))
4335        ,@(if (or references message-id)
4336              `((References . ,(concat (or references "") (and references " ")
4337                                       (or message-id "")))))
4338        ,@(when (and mct
4339                     (not (or (equal (downcase mct) "never")
4340                              (equal (downcase mct) "nobody"))))
4341            (list (cons 'Cc (if (or (equal (downcase mct) "always")
4342                                    (equal (downcase mct) "poster"))
4343                                (or mrt reply-to from "")
4344                              mct)))))
4345
4346      cur)
4347
4348     (setq message-reply-headers
4349           (vector 0 subject from date message-id references 0 0 ""))))
4350
4351
4352 ;;;###autoload
4353 (defun message-cancel-news (&optional arg)
4354   "Cancel an article you posted.
4355 If ARG, allow editing of the cancellation message."
4356   (interactive "P")
4357   (unless (message-news-p)
4358     (error "This is not a news article; canceling is impossible"))
4359   (let (from newsgroups message-id distribution buf sender)
4360     (save-excursion
4361       ;; Get header info from original article.
4362       (save-restriction
4363         (message-narrow-to-head-1)
4364         (setq from (message-fetch-field "from")
4365               sender (message-fetch-field "sender")
4366               newsgroups (message-fetch-field "newsgroups")
4367               message-id (message-fetch-field "message-id" t)
4368               distribution (message-fetch-field "distribution")))
4369       ;; Make sure that this article was written by the user.
4370       (unless (or (message-gnksa-enable-p 'cancel-messages)
4371                   (and sender
4372                        (string-equal
4373                         (downcase sender)
4374                         (downcase (message-make-sender))))
4375                   (string-equal
4376                    (downcase (cadr (mail-extract-address-components from)))
4377                    (downcase (cadr (mail-extract-address-components
4378                                     (message-make-from))))))
4379         (error "This article is not yours"))
4380       (when (yes-or-no-p "Do you really want to cancel this article? ")
4381         ;; Make control message.
4382         (if arg
4383             (message-news)
4384           (setq buf (set-buffer (get-buffer-create " *message cancel*"))))
4385         (erase-buffer)
4386         (insert "Newsgroups: " newsgroups "\n"
4387                 "From: " from "\n"
4388                 "Subject: cmsg cancel " message-id "\n"
4389                 "Control: cancel " message-id "\n"
4390                 (if distribution
4391                     (concat "Distribution: " distribution "\n")
4392                   "")
4393                 mail-header-separator "\n"
4394                 message-cancel-message)
4395         (run-hooks 'message-cancel-hook)
4396         (unless arg
4397           (message "Canceling your article...")
4398           (if (let ((message-syntax-checks
4399                      'dont-check-for-anything-just-trust-me))
4400                 (funcall message-send-news-function))
4401               (message "Canceling your article...done"))
4402           (kill-buffer buf))))))
4403
4404 ;;;###autoload
4405 (defun message-supersede ()
4406   "Start composing a message to supersede the current message.
4407 This is done simply by taking the old article and adding a Supersedes
4408 header line with the old Message-ID."
4409   (interactive)
4410   (let ((cur (current-buffer))
4411         (sender (message-fetch-field "sender"))
4412         (from (message-fetch-field "from")))
4413     ;; Check whether the user owns the article that is to be superseded.
4414     (unless (or (message-gnksa-enable-p 'cancel-messages)
4415                 (and sender
4416                      (string-equal
4417                       (downcase sender)
4418                       (downcase (message-make-sender))))
4419                 (string-equal
4420                  (downcase (cadr (mail-extract-address-components from)))
4421                  (downcase (cadr (mail-extract-address-components
4422                                   (message-make-from))))))
4423       (error "This article is not yours"))
4424     ;; Get a normal message buffer.
4425     (message-pop-to-buffer (message-buffer-name "supersede"))
4426     (insert-buffer-substring cur)
4427     (mime-to-mml)
4428     (message-narrow-to-head-1)
4429     ;; Remove unwanted headers.
4430     (when message-ignored-supersedes-headers
4431       (message-remove-header message-ignored-supersedes-headers t))
4432     (goto-char (point-min))
4433     (if (not (re-search-forward "^Message-ID: " nil t))
4434         (error "No Message-ID in this article")
4435       (replace-match "Supersedes: " t t))
4436     (goto-char (point-max))
4437     (insert mail-header-separator)
4438     (widen)
4439     (forward-line 1)))
4440
4441 ;;;###autoload
4442 (defun message-recover ()
4443   "Reread contents of current buffer from its last auto-save file."
4444   (interactive)
4445   (let ((file-name (make-auto-save-file-name)))
4446     (cond ((save-window-excursion
4447              (if (not (eq system-type 'vax-vms))
4448                  (with-output-to-temp-buffer "*Directory*"
4449                    (with-current-buffer standard-output
4450                      (fundamental-mode)) ; for Emacs 20.4+
4451                    (buffer-disable-undo standard-output)
4452                    (let ((default-directory "/"))
4453                      (call-process
4454                       "ls" nil standard-output nil "-l" file-name))))
4455              (yes-or-no-p (format "Recover auto save file %s? " file-name)))
4456            (let ((buffer-read-only nil))
4457              (erase-buffer)
4458              (insert-file-contents file-name nil)))
4459           (t (error "message-recover cancelled")))))
4460
4461 ;;; Washing Subject:
4462
4463 (defun message-wash-subject (subject)
4464   "Remove junk like \"Re:\", \"(fwd)\", etc. added to subject string SUBJECT.
4465 Previous forwarders, replyers, etc. may add it."
4466   (with-temp-buffer
4467     (insert-string subject)
4468     (goto-char (point-min))
4469     ;; strip Re/Fwd stuff off the beginning
4470     (while (re-search-forward
4471             "\\([Rr][Ee]:\\|[Ff][Ww][Dd]\\(\\[[0-9]*\\]\\)?:\\|[Ff][Ww]:\\)" nil t)
4472       (replace-match ""))
4473
4474     ;; and gnus-style forwards [foo@bar.com] subject
4475     (goto-char (point-min))
4476     (while (re-search-forward "\\[[^ \t]*\\(@\\|\\.\\)[^ \t]*\\]" nil t)
4477       (replace-match ""))
4478
4479     ;; and off the end
4480     (goto-char (point-max))
4481     (while (re-search-backward "([Ff][Ww][Dd])" nil t)
4482       (replace-match ""))
4483
4484     ;; and finally, any whitespace that was left-over
4485     (goto-char (point-min))
4486     (while (re-search-forward "^[ \t]+" nil t)
4487       (replace-match ""))
4488     (goto-char (point-max))
4489     (while (re-search-backward "[ \t]+$" nil t)
4490       (replace-match ""))
4491
4492     (buffer-string)))
4493
4494 ;;; Forwarding messages.
4495
4496 (defvar message-forward-decoded-p nil
4497   "Non-nil means the original message is decoded.")
4498
4499 (defun message-forward-subject-author-subject (subject)
4500   "Generate a SUBJECT for a forwarded message.
4501 The form is: [Source] Subject, where if the original message was mail,
4502 Source is the sender, and if the original message was news, Source is
4503 the list of newsgroups is was posted to."
4504   (concat "["
4505           (let ((prefix
4506                  (or (message-fetch-field
4507                       (if (message-news-p) "newsgroups" "from"))
4508                      "(nowhere)")))
4509             (if message-forward-decoded-p
4510                 prefix
4511               (mail-decode-encoded-word-string prefix)))
4512           "] " subject))
4513
4514 (defun message-forward-subject-fwd (subject)
4515   "Generate a SUBJECT for a forwarded message.
4516 The form is: Fwd: Subject, where Subject is the original subject of
4517 the message."
4518   (concat "Fwd: " subject))
4519
4520 (defun message-make-forward-subject ()
4521   "Return a Subject header suitable for the message in the current buffer."
4522   (save-excursion
4523     (save-restriction
4524       (message-narrow-to-head-1)
4525       (let ((funcs message-make-forward-subject-function)
4526             (subject (message-fetch-field "Subject")))
4527         (setq subject
4528               (if subject
4529                   (if message-forward-decoded-p
4530                       subject
4531                     (mail-decode-encoded-word-string subject))
4532                 ""))
4533         (if message-wash-forwarded-subjects
4534             (setq subject (message-wash-subject subject)))
4535         ;; Make sure funcs is a list.
4536         (and funcs
4537              (not (listp funcs))
4538              (setq funcs (list funcs)))
4539         ;; Apply funcs in order, passing subject generated by previous
4540         ;; func to the next one.
4541         (while funcs
4542           (when (message-functionp (car funcs))
4543             (setq subject (funcall (car funcs) subject)))
4544           (setq funcs (cdr funcs)))
4545         subject))))
4546
4547 (eval-when-compile
4548   (defvar gnus-article-decoded-p))
4549
4550 ;;;###autoload
4551 (defun message-forward (&optional news digest)
4552   "Forward the current message via mail.
4553 Optional NEWS will use news to forward instead of mail.
4554 Optional DIGEST will use digest to forward."
4555   (interactive "P")
4556   (let* ((cur (current-buffer))
4557          (message-forward-decoded-p
4558           (if (local-variable-p 'gnus-article-decoded-p (current-buffer))
4559               gnus-article-decoded-p ;; In an article buffer.
4560             message-forward-decoded-p))
4561          (subject (message-make-forward-subject))
4562          art-beg)
4563     (if news
4564         (message-news nil subject)
4565       (message-mail nil subject))
4566     ;; Put point where we want it before inserting the forwarded
4567     ;; message.
4568     (if message-forward-before-signature
4569         (message-goto-body)
4570       (goto-char (point-max)))
4571     (if message-forward-as-mime
4572         (if digest
4573             (insert "\n<#multipart type=digest>\n")
4574           (if message-forward-show-mml
4575               (insert "\n\n<#mml type=message/rfc822 disposition=inline>\n")
4576             (insert "\n\n<#part type=message/rfc822 disposition=inline raw=t>\n")))
4577       (insert "\n-------------------- Start of forwarded message --------------------\n"))
4578     (let ((b (point)) e)
4579       (if digest
4580           (if message-forward-as-mime
4581               (insert-buffer-substring cur)
4582             (mml-insert-buffer cur))
4583         (if (and message-forward-show-mml
4584                  (not message-forward-decoded-p))
4585             (insert
4586              (with-temp-buffer
4587                (mm-disable-multibyte-mule4) ;; Must copy buffer in unibyte mode
4588                (insert
4589                 (with-current-buffer cur
4590                   (mm-string-as-unibyte (buffer-string))))
4591                (mm-enable-multibyte-mule4)
4592                (mime-to-mml)
4593                (goto-char (point-min))
4594                (when (looking-at "From ")
4595                  (replace-match "X-From-Line: "))
4596                (buffer-string)))
4597           (save-restriction
4598             (narrow-to-region (point) (point))
4599             (mml-insert-buffer cur)
4600             (goto-char (point-min))
4601             (when (looking-at "From ")
4602               (replace-match "X-From-Line: "))
4603             (goto-char (point-max)))))
4604       (setq e (point))
4605       (if message-forward-as-mime
4606           (if digest
4607               (insert "<#/multipart>\n")
4608             (if message-forward-show-mml
4609                 (insert "<#/mml>\n")
4610               (insert "<#/part>\n")))
4611         (insert "\n-------------------- End of forwarded message --------------------\n"))
4612       (if (and digest message-forward-as-mime)
4613           (save-restriction
4614             (narrow-to-region b e)
4615             (goto-char b)
4616             (narrow-to-region (point)
4617                               (or (search-forward "\n\n" nil t) (point)))
4618             (delete-region (point-min) (point-max)))
4619         (when (and (not current-prefix-arg)
4620                    message-forward-ignored-headers)
4621           (save-restriction
4622             (narrow-to-region b e)
4623             (goto-char b)
4624             (narrow-to-region (point)
4625                               (or (search-forward "\n\n" nil t) (point)))
4626             (message-remove-header message-forward-ignored-headers t)))))
4627     (message-position-point)))
4628
4629 ;;;###autoload
4630 (defun message-resend (address)
4631   "Resend the current article to ADDRESS."
4632   (interactive
4633    (list (message-read-from-minibuffer "Resend message to: ")))
4634   (message "Resending message to %s..." address)
4635   (save-excursion
4636     (let ((cur (current-buffer))
4637           beg)
4638       ;; We first set up a normal mail buffer.
4639       (unless (message-mail-user-agent)
4640         (set-buffer (get-buffer-create " *message resend*"))
4641         (erase-buffer))
4642       (let ((message-this-is-mail t))
4643         (message-setup `((To . ,address))))
4644       ;; Insert our usual headers.
4645       (message-generate-headers '(From Date To))
4646       (message-narrow-to-headers)
4647       ;; Rename them all to "Resent-*".
4648       (while (re-search-forward "^[A-Za-z]" nil t)
4649         (forward-char -1)
4650         (insert "Resent-"))
4651       (widen)
4652       (forward-line)
4653       (delete-region (point) (point-max))
4654       (setq beg (point))
4655       ;; Insert the message to be resent.
4656       (insert-buffer-substring cur)
4657       (goto-char (point-min))
4658       (search-forward "\n\n")
4659       (forward-char -1)
4660       (save-restriction
4661         (narrow-to-region beg (point))
4662         (message-remove-header message-ignored-resent-headers t)
4663         (goto-char (point-max)))
4664       (insert mail-header-separator)
4665       ;; Rename all old ("Also-")Resent headers.
4666       (while (re-search-backward "^\\(Also-\\)*Resent-" beg t)
4667         (beginning-of-line)
4668         (insert "Also-"))
4669       ;; Quote any "From " lines at the beginning.
4670       (goto-char beg)
4671       (when (looking-at "From ")
4672         (replace-match "X-From-Line: "))
4673       ;; Send it.
4674       (let ((message-inhibit-body-encoding t)
4675             message-required-mail-headers)
4676         (message-send-mail))
4677       (kill-buffer (current-buffer)))
4678     (message "Resending message to %s...done" address)))
4679
4680 ;;;###autoload
4681 (defun message-bounce ()
4682   "Re-mail the current message.
4683 This only makes sense if the current message is a bounce message that
4684 contains some mail you have written which has been bounced back to
4685 you."
4686   (interactive)
4687   (let ((handles (mm-dissect-buffer t))
4688         boundary)
4689     (message-pop-to-buffer (message-buffer-name "bounce"))
4690     (if (stringp (car handles))
4691         ;; This is a MIME bounce.
4692         (mm-insert-part (car (last handles)))
4693       ;; This is a non-MIME bounce, so we try to remove things
4694       ;; manually.
4695       (mm-insert-part handles)
4696       (undo-boundary)
4697       (goto-char (point-min))
4698       (search-forward "\n\n" nil t)
4699       (if (or (and (re-search-forward message-unsent-separator nil t)
4700                    (forward-line 1))
4701               (re-search-forward "^Return-Path:.*\n" nil t))
4702           ;; We remove everything before the bounced mail.
4703           (delete-region
4704            (point-min)
4705            (if (re-search-forward "^[^ \n\t]+:" nil t)
4706                (match-beginning 0)
4707              (point)))
4708         (when (re-search-backward "^.?From .*\n" nil t)
4709           (delete-region (match-beginning 0) (match-end 0)))))
4710     (mm-enable-multibyte)
4711     (mime-to-mml)
4712     (save-restriction
4713       (message-narrow-to-head-1)
4714       (message-remove-header message-ignored-bounced-headers t)
4715       (goto-char (point-max))
4716       (insert mail-header-separator))
4717     (message-position-point)))
4718
4719 ;;;
4720 ;;; Interactive entry points for new message buffers.
4721 ;;;
4722
4723 ;;;###autoload
4724 (defun message-mail-other-window (&optional to subject)
4725   "Like `message-mail' command, but display mail buffer in another window."
4726   (interactive)
4727   (unless (message-mail-user-agent)
4728     (let ((pop-up-windows t)
4729           (special-display-buffer-names nil)
4730           (special-display-regexps nil)
4731           (same-window-buffer-names nil)
4732           (same-window-regexps nil))
4733       (message-pop-to-buffer (message-buffer-name "mail" to))))
4734   (let ((message-this-is-mail t))
4735     (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))
4736                    nil nil 'switch-to-buffer-other-window)))
4737
4738 ;;;###autoload
4739 (defun message-mail-other-frame (&optional to subject)
4740   "Like `message-mail' command, but display mail buffer in another frame."
4741   (interactive)
4742   (unless (message-mail-user-agent)
4743     (let ((pop-up-frames t)
4744           (special-display-buffer-names nil)
4745           (special-display-regexps nil)
4746           (same-window-buffer-names nil)
4747           (same-window-regexps nil))
4748       (message-pop-to-buffer (message-buffer-name "mail" to))))
4749   (let ((message-this-is-mail t))
4750     (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))
4751                    nil nil 'switch-to-buffer-other-frame)))
4752
4753 ;;;###autoload
4754 (defun message-news-other-window (&optional newsgroups subject)
4755   "Start editing a news article to be sent."
4756   (interactive)
4757   (let ((pop-up-windows t)
4758         (special-display-buffer-names nil)
4759         (special-display-regexps nil)
4760         (same-window-buffer-names nil)
4761         (same-window-regexps nil))
4762     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
4763   (let ((message-this-is-news t))
4764     (message-setup `((Newsgroups . ,(or newsgroups ""))
4765                      (Subject . ,(or subject ""))))))
4766
4767 ;;;###autoload
4768 (defun message-news-other-frame (&optional newsgroups subject)
4769   "Start editing a news article to be sent."
4770   (interactive)
4771   (let ((pop-up-frames t)
4772         (special-display-buffer-names nil)
4773         (special-display-regexps nil)
4774         (same-window-buffer-names nil)
4775         (same-window-regexps nil))
4776     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
4777   (let ((message-this-is-news t))
4778     (message-setup `((Newsgroups . ,(or newsgroups ""))
4779                      (Subject . ,(or subject ""))))))
4780
4781 ;;; underline.el
4782
4783 ;; This code should be moved to underline.el (from which it is stolen).
4784
4785 ;;;###autoload
4786 (defun bold-region (start end)
4787   "Bold all nonblank characters in the region.
4788 Works by overstriking characters.
4789 Called from program, takes two arguments START and END
4790 which specify the range to operate on."
4791   (interactive "r")
4792   (save-excursion
4793     (let ((end1 (make-marker)))
4794       (move-marker end1 (max start end))
4795       (goto-char (min start end))
4796       (while (< (point) end1)
4797         (or (looking-at "[_\^@- ]")
4798             (insert (char-after) "\b"))
4799         (forward-char 1)))))
4800
4801 ;;;###autoload
4802 (defun unbold-region (start end)
4803   "Remove all boldness (overstruck characters) in the region.
4804 Called from program, takes two arguments START and END
4805 which specify the range to operate on."
4806   (interactive "r")
4807   (save-excursion
4808     (let ((end1 (make-marker)))
4809       (move-marker end1 (max start end))
4810       (goto-char (min start end))
4811       (while (re-search-forward "\b" end1 t)
4812         (if (eq (char-after) (char-after (- (point) 2)))
4813             (delete-char -2))))))
4814
4815 (defalias 'message-exchange-point-and-mark 'exchange-point-and-mark)
4816
4817 ;; Support for toolbar
4818 (eval-when-compile
4819   (defvar tool-bar-map)
4820   (defvar tool-bar-mode))
4821
4822 (defun message-tool-bar-map ()
4823   (or message-tool-bar-map
4824       (setq message-tool-bar-map
4825             (and (fboundp 'tool-bar-add-item-from-menu)
4826                  tool-bar-mode
4827                  (let ((tool-bar-map (copy-keymap tool-bar-map))
4828                        (load-path (mm-image-load-path)))
4829                    ;; Zap some items which aren't so relevant and take
4830                    ;; up space.
4831                    (dolist (key '(print-buffer kill-buffer save-buffer
4832                                                write-file dired open-file))
4833                      (define-key tool-bar-map (vector key) nil))
4834                    (tool-bar-add-item-from-menu
4835                     'message-send-and-exit "mail_send" message-mode-map)
4836                    (tool-bar-add-item-from-menu
4837                     'message-kill-buffer "close" message-mode-map)
4838                    (tool-bar-add-item-from-menu
4839                     'message-dont-send "cancel" message-mode-map)
4840                    (tool-bar-add-item-from-menu
4841                     'mml-attach-file "attach" message-mode-map)
4842                    (tool-bar-add-item-from-menu
4843                     'ispell-message "spell" message-mode-map)
4844                    tool-bar-map)))))
4845
4846 ;;; Group name completion.
4847
4848 (defvar message-newgroups-header-regexp
4849   "^\\(Newsgroups\\|Followup-To\\|Posted-To\\|Gcc\\):"
4850   "Regexp that match headers that lists groups.")
4851
4852 (defvar message-completion-alist
4853   (list (cons message-newgroups-header-regexp 'message-expand-group)
4854         '("^\\(Resent-\\)?\\(To\\|B?Cc\\):" . message-expand-name))
4855   "Alist of (RE . FUN).  Use FUN for completion on header lines matching RE.")
4856
4857 (defvar message-tab-body-function 'indent-relative
4858   "*Function to execute when `message-tab' (TAB) is executed in the body.")
4859
4860 (defun message-tab ()
4861   "Complete names according to `message-completion-alist'.
4862 Do an `indent-relative' if not in those headers."
4863   (interactive)
4864   (let ((alist message-completion-alist))
4865     (while (and alist
4866                 (let ((mail-abbrev-mode-regexp (caar alist)))
4867                   (not (mail-abbrev-in-expansion-header-p))))
4868       (setq alist (cdr alist)))
4869     (funcall (or (cdar alist) message-tab-body-function))))
4870
4871 (defun message-expand-group ()
4872   "Expand the group name under point."
4873   (let* ((b (save-excursion
4874               (save-restriction
4875                 (narrow-to-region
4876                  (save-excursion
4877                    (beginning-of-line)
4878                    (skip-chars-forward "^:")
4879                    (1+ (point)))
4880                  (point))
4881                 (skip-chars-backward "^, \t\n") (point))))
4882          (completion-ignore-case t)
4883          (string (buffer-substring b (progn (skip-chars-forward "^,\t\n ")
4884                                             (point))))
4885          (hashtb (and (boundp 'gnus-active-hashtb) gnus-active-hashtb))
4886          (completions (all-completions string hashtb))
4887          comp)
4888     (delete-region b (point))
4889     (cond
4890      ((= (length completions) 1)
4891       (if (string= (car completions) string)
4892           (progn
4893             (insert string)
4894             (message "Only matching group"))
4895         (insert (car completions))))
4896      ((and (setq comp (try-completion string hashtb))
4897            (not (string= comp string)))
4898       (insert comp))
4899      (t
4900       (insert string)
4901       (if (not comp)
4902           (message "No matching groups")
4903         (save-selected-window
4904           (pop-to-buffer "*Completions*")
4905           (buffer-disable-undo)
4906           (let ((buffer-read-only nil))
4907             (erase-buffer)
4908             (let ((standard-output (current-buffer)))
4909               (display-completion-list (sort completions 'string<)))
4910             (goto-char (point-min))
4911             (delete-region (point) (progn (forward-line 3) (point))))))))))
4912
4913 (defun message-expand-name ()
4914   (if (fboundp 'bbdb-complete-name)
4915       (bbdb-complete-name)
4916     (expand-abbrev)))
4917
4918 ;;; Help stuff.
4919
4920 (defun message-talkative-question (ask question show &rest text)
4921   "Call FUNCTION with argument QUESTION; optionally display TEXT... args.
4922 If SHOW is non-nil, the arguments TEXT... are displayed in a temp buffer.
4923 The following arguments may contain lists of values."
4924   (if (and show
4925            (setq text (message-flatten-list text)))
4926       (save-window-excursion
4927         (save-excursion
4928           (with-output-to-temp-buffer " *MESSAGE information message*"
4929             (set-buffer " *MESSAGE information message*")
4930             (fundamental-mode)          ; for Emacs 20.4+
4931             (mapcar 'princ text)
4932             (goto-char (point-min))))
4933         (funcall ask question))
4934     (funcall ask question)))
4935
4936 (defun message-flatten-list (list)
4937   "Return a new, flat list that contains all elements of LIST.
4938
4939 \(message-flatten-list '(1 (2 3 (4 5 (6))) 7))
4940 => (1 2 3 4 5 6 7)"
4941   (cond ((consp list)
4942          (apply 'append (mapcar 'message-flatten-list list)))
4943         (list
4944          (list list))))
4945
4946 (defun message-generate-new-buffer-clone-locals (name &optional varstr)
4947   "Create and return a buffer with name based on NAME using `generate-new-buffer.'
4948 Then clone the local variables and values from the old buffer to the
4949 new one, cloning only the locals having a substring matching the
4950 regexp varstr."
4951   (let ((oldbuf (current-buffer)))
4952     (save-excursion
4953       (set-buffer (generate-new-buffer name))
4954       (message-clone-locals oldbuf varstr)
4955       (current-buffer))))
4956
4957 (defun message-clone-locals (buffer &optional varstr)
4958   "Clone the local variables from BUFFER to the current buffer."
4959   (let ((locals (save-excursion
4960                   (set-buffer buffer)
4961                   (buffer-local-variables)))
4962         (regexp "^gnus\\|^nn\\|^message\\|^user-mail-address"))
4963     (mapcar
4964      (lambda (local)
4965        (when (and (consp local)
4966                   (car local)
4967                   (string-match regexp (symbol-name (car local)))
4968                   (or (null varstr)
4969                       (string-match varstr (symbol-name (car local)))))
4970          (ignore-errors
4971            (set (make-local-variable (car local))
4972                 (cdr local)))))
4973      locals)))
4974
4975 ;;; Miscellaneous functions
4976
4977 (defsubst message-replace-chars-in-string (string from to)
4978   (mm-subst-char-in-string from to string))
4979
4980 ;;;
4981 ;;; MIME functions
4982 ;;;
4983
4984 (defvar message-inhibit-body-encoding nil)
4985
4986 (defun message-encode-message-body ()
4987   (unless message-inhibit-body-encoding
4988     (let ((mail-parse-charset (or mail-parse-charset
4989                                   message-default-charset))
4990           (case-fold-search t)
4991           lines content-type-p)
4992       (message-goto-body)
4993       (save-restriction
4994         (narrow-to-region (point) (point-max))
4995         (let ((new (mml-generate-mime)))
4996           (when new
4997             (delete-region (point-min) (point-max))
4998             (insert new)
4999             (goto-char (point-min))
5000             (if (eq (aref new 0) ?\n)
5001                 (delete-char 1)
5002               (search-forward "\n\n")
5003               (setq lines (buffer-substring (point-min) (1- (point))))
5004               (delete-region (point-min) (point))))))
5005       (save-restriction
5006         (message-narrow-to-headers-or-head)
5007         (message-remove-header "Mime-Version")
5008         (goto-char (point-max))
5009         (insert "MIME-Version: 1.0\n")
5010         (when lines
5011           (insert lines))
5012         (setq content-type-p
5013               (or mml-boundary
5014                   (re-search-backward "^Content-Type:" nil t))))
5015       (save-restriction
5016         (message-narrow-to-headers-or-head)
5017         (message-remove-first-header "Content-Type")
5018         (message-remove-first-header "Content-Transfer-Encoding"))
5019       ;; We always make sure that the message has a Content-Type header.
5020       ;; This is because some broken MTAs and MUAs get awfully confused
5021       ;; when confronted with a message with a MIME-Version header and
5022       ;; without a Content-Type header.  For instance, Solaris'
5023       ;; /usr/bin/mail.
5024       (unless content-type-p
5025         (goto-char (point-min))
5026         (re-search-forward "^MIME-Version:")
5027         (forward-line 1)
5028         (insert "Content-Type: text/plain; charset=us-ascii\n")))))
5029
5030 (defun message-read-from-minibuffer (prompt)
5031   "Read from the minibuffer while providing abbrev expansion."
5032   (if (fboundp 'mail-abbrevs-setup)
5033       (let ((mail-abbrev-mode-regexp "")
5034             (minibuffer-setup-hook 'mail-abbrevs-setup)
5035             (minibuffer-local-map message-minibuffer-local-map))
5036         (read-from-minibuffer prompt))
5037     (let ((minibuffer-setup-hook 'mail-abbrev-minibuffer-setup-hook)
5038           (minibuffer-local-map message-minibuffer-local-map))
5039       (read-string prompt))))
5040
5041 (defun message-use-alternative-email-as-from ()
5042   (require 'mail-utils)
5043   (let* ((fields '("To" "Cc"))
5044          (emails
5045           (split-string
5046            (mail-strip-quoted-names
5047             (mapconcat 'message-fetch-reply-field fields ","))
5048            "[ \f\t\n\r\v,]+"))
5049          email)
5050     (while emails
5051       (if (string-match message-alternative-emails (car emails))
5052           (setq email (car emails)
5053                 emails nil))
5054       (pop emails))
5055     (unless (or (not email) (equal email user-mail-address))
5056       (goto-char (point-max))
5057       (insert "From: " email "\n"))))
5058
5059 (defun message-options-get (symbol)
5060   (cdr (assq symbol message-options)))
5061
5062 (defun message-options-set (symbol value)
5063   (let ((the-cons (assq symbol message-options)))
5064     (if the-cons
5065         (if value
5066             (setcdr the-cons value)
5067           (setq message-options (delq the-cons message-options)))
5068       (and value
5069            (push (cons symbol value) message-options))))
5070   value)
5071
5072 (defun message-options-set-recipient ()
5073   (save-restriction
5074     (message-narrow-to-headers-or-head)
5075     (message-options-set 'message-sender
5076                          (mail-strip-quoted-names
5077                           (message-fetch-field "from")))
5078     (message-options-set 'message-recipients
5079                          (mail-strip-quoted-names
5080                           (let ((to (message-fetch-field "to"))
5081                                 (cc (message-fetch-field "cc"))
5082                                 (bcc (message-fetch-field "bcc")))
5083                             (concat
5084                              (or to "")
5085                              (if (and to cc) ", ")
5086                              (or cc "")
5087                              (if (and (or to cc) bcc) ", ")
5088                              (or bcc "")))))))
5089
5090 (when (featurep 'xemacs)
5091   (require 'messagexmas)
5092   (message-xmas-redefine))
5093
5094 (provide 'message)
5095
5096 (run-hooks 'message-load-hook)
5097
5098 ;; Local Variables:
5099 ;; coding: iso-8859-1
5100 ;; End:
5101
5102 ;;; message.el ends here