Synch with Oort Gnus.
[elisp/gnus.git-] / lisp / message.el
1 ;;; message.el --- composing mail and news messages
2 ;; Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002
3 ;;        Free Software Foundation, Inc.
4
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;;      MORIOKA Tomohiko <morioka@jaist.ac.jp>
7 ;;      Shuhei KOBAYASHI <shuhei-k@jaist.ac.jp>
8 ;;      Keiichi Suzuki   <kei-suzu@mail.wbs.ne.jp>
9 ;;      Tatsuya Ichikawa <t-ichi@po.shiojiri.ne.jp>
10 ;;      Katsumi Yamaoka  <yamaoka@jpl.org>
11 ;;      Kiyokazu SUTO    <suto@merry.xmath.ous.ac.jp>
12 ;; Keywords: mail, news, MIME
13
14 ;; This file is part of GNU Emacs.
15
16 ;; GNU Emacs is free software; you can redistribute it and/or modify
17 ;; it under the terms of the GNU General Public License as published by
18 ;; the Free Software Foundation; either version 2, or (at your option)
19 ;; any later version.
20
21 ;; GNU Emacs is distributed in the hope that it will be useful,
22 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
23 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24 ;; GNU General Public License for more details.
25
26 ;; You should have received a copy of the GNU General Public License
27 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
28 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
29 ;; Boston, MA 02111-1307, USA.
30
31 ;;; Commentary:
32
33 ;; This mode provides mail-sending facilities from within Emacs.  It
34 ;; consists mainly of large chunks of code from the sendmail.el,
35 ;; gnus-msg.el and rnewspost.el files.
36
37 ;;; Code:
38
39 (eval-when-compile
40   (require 'cl)
41   (require 'smtp)
42   (defvar gnus-list-identifiers)) ; gnus-sum is required where necessary
43 (eval-and-compile
44   (if (boundp 'MULE)
45       (progn
46         (require 'base64)
47         (require 'canlock-om))
48     (require 'canlock)))
49 (require 'mailheader)
50 (require 'nnheader)
51 ;; This is apparently necessary even though things are autoloaded.
52 ;; Because we dynamically bind mail-abbrev-mode-regexp, we'd better
53 ;; require mailabbrev here.
54 (if (featurep 'xemacs)
55     (require 'mail-abbrevs)
56   (require 'mailabbrev))
57 (require 'mime-edit)
58 (eval-when-compile (require 'static))
59
60 ;; Avoid byte-compile warnings.
61 (eval-when-compile
62   (require 'mail-parse)
63   (require 'mml))
64
65 (require 'rfc822)
66 (eval-and-compile
67   (autoload 'sha1 "sha1-el")
68   (autoload 'customize-save-variable "cus-edit"));; for Mule 2.
69
70 (defgroup message '((user-mail-address custom-variable)
71                     (user-full-name custom-variable))
72   "Mail and news message composing."
73   :link '(custom-manual "(message)Top")
74   :group 'mail
75   :group 'news)
76
77 (put 'user-mail-address 'custom-type 'string)
78 (put 'user-full-name 'custom-type 'string)
79
80 (defgroup message-various nil
81   "Various Message Variables"
82   :link '(custom-manual "(message)Various Message Variables")
83   :group 'message)
84
85 (defgroup message-buffers nil
86   "Message Buffers"
87   :link '(custom-manual "(message)Message Buffers")
88   :group 'message)
89
90 (defgroup message-sending nil
91   "Message Sending"
92   :link '(custom-manual "(message)Sending Variables")
93   :group 'message)
94
95 (defgroup message-interface nil
96   "Message Interface"
97   :link '(custom-manual "(message)Interface")
98   :group 'message)
99
100 (defgroup message-forwarding nil
101   "Message Forwarding"
102   :link '(custom-manual "(message)Forwarding")
103   :group 'message-interface)
104
105 (defgroup message-insertion nil
106   "Message Insertion"
107   :link '(custom-manual "(message)Insertion")
108   :group 'message)
109
110 (defgroup message-headers nil
111   "Message Headers"
112   :link '(custom-manual "(message)Message Headers")
113   :group 'message)
114
115 (defgroup message-news nil
116   "Composing News Messages"
117   :group 'message)
118
119 (defgroup message-mail nil
120   "Composing Mail Messages"
121   :group 'message)
122
123 (defgroup message-faces nil
124   "Faces used for message composing."
125   :group 'message
126   :group 'faces)
127
128 (defgroup message-frames nil
129   "Message frames"
130   :group 'message)
131
132 (defcustom message-directory "~/Mail/"
133   "*Directory from which all other mail file variables are derived."
134   :group 'message-various
135   :type 'directory)
136
137 (defcustom message-max-buffers 10
138   "*How many buffers to keep before starting to kill them off."
139   :group 'message-buffers
140   :type 'integer)
141
142 (defcustom message-send-rename-function nil
143   "Function called to rename the buffer after sending it."
144   :group 'message-buffers
145   :type '(choice function (const nil)))
146
147 (defcustom message-fcc-handler-function 'message-output
148   "*A function called to save outgoing articles.
149 This function will be called with the name of the file to store the
150 article in.  The default function is `message-output' which saves in Unix
151 mailbox format."
152   :type '(radio (function-item message-output)
153                 (function :tag "Other"))
154   :group 'message-sending)
155
156 (defcustom message-encode-function 'message-maybe-encode
157   "*A function called to encode messages."
158   :group 'message-sending
159   :type 'function)
160
161 (defcustom message-8bit-encoding-list '(8bit binary)
162   "*8bit encoding type in Content-Transfer-Encoding field."
163   :group 'message-sending
164   :type '(repeat (symbol :tag "Type")))
165
166 (defcustom message-fcc-externalize-attachments nil
167   "If non-nil, attachments are included as external parts in Fcc copies."
168   :type 'boolean
169   :group 'message-sending)
170
171 (defcustom message-courtesy-message
172   "The following message is a courtesy copy of an article\nthat has been posted to %s as well.\n\n"
173   "*This is inserted at the start of a mailed copy of a posted message.
174 If the string contains the format spec \"%s\", the Newsgroups
175 the article has been posted to will be inserted there.
176 If this variable is nil, no such courtesy message will be added."
177   :group 'message-sending
178   :type 'string)
179
180 (defcustom message-ignored-bounced-headers "^\\(Received\\|Return-Path\\):"
181   "*Regexp that matches headers to be removed in resent bounced mail."
182   :group 'message-interface
183   :type 'regexp)
184
185 (defcustom message-bounce-setup-function 'message-bounce-setup-for-mime-edit
186   "Function to setup a re-sending bounced message."
187   :group 'message-sending
188   :type 'function)
189
190 ;;;###autoload
191 (defcustom message-from-style 'default
192   "*Specifies how \"From\" headers look.
193
194 If nil, they contain just the return address like:
195         king@grassland.com
196 If `parens', they look like:
197         king@grassland.com (Elvis Parsley)
198 If `angles', they look like:
199         Elvis Parsley <king@grassland.com>
200
201 Otherwise, most addresses look like `angles', but they look like
202 `parens' if `angles' would need quoting and `parens' would not."
203   :type '(choice (const :tag "simple" nil)
204                  (const parens)
205                  (const angles)
206                  (const default))
207   :group 'message-headers)
208
209 (defcustom message-insert-canlock t
210   "Whether to insert a Cancel-Lock header in news postings."
211   :version "21.3"
212   :group 'message-headers
213   :type 'boolean)
214
215 (defcustom message-syntax-checks 
216   (if message-insert-canlock '((sender . disabled)) nil)
217   ;; Guess this one shouldn't be easy to customize...
218   "*Controls what syntax checks should not be performed on outgoing posts.
219 To disable checking of long signatures, for instance, add
220  `(signature . disabled)' to this list.
221
222 Don't touch this variable unless you really know what you're doing.
223
224 Checks include `subject-cmsg', `multiple-headers', `sendsys',
225 `message-id', `from', `long-lines', `control-chars', `size',
226 `new-text', `quoting-style', `redirected-followup', `signature',
227 `approved', `sender', `empty', `empty-headers', `message-id', `from',
228 `subject', `shorten-followup-to', `existing-newsgroups',
229 `buffer-file-name', `unchanged', `newsgroups', `reply-to'."
230   :group 'message-news
231   :type '(repeat sexp))                 ; Fixme: improve this
232
233 (defcustom message-required-news-headers
234   '(From Newsgroups Subject Date Message-ID
235          (optional . Organization) Lines
236          (optional . User-Agent))
237   "*Headers to be generated or prompted for when posting an article.
238 RFC977 and RFC1036 require From, Date, Newsgroups, Subject,
239 Message-ID.  Organization, Lines, In-Reply-To, Expires, and
240 User-Agent are optional.  If don't you want message to insert some
241 header, remove it from this list."
242   :group 'message-news
243   :group 'message-headers
244   :type '(repeat sexp))
245
246 (defcustom message-required-mail-headers
247   '(From Subject Date (optional . In-Reply-To) Message-ID Lines
248          (optional . User-Agent))
249   "*Headers to be generated or prompted for when mailing a message.
250 It is recommended that From, Date, To, Subject and Message-ID be
251 included.  Organization, Lines and User-Agent are optional."
252   :group 'message-mail
253   :group 'message-headers
254   :type '(repeat sexp))
255
256 (defcustom message-deletable-headers '(Message-ID Date Lines)
257   "Headers to be deleted if they already exist and were generated by message previously."
258   :group 'message-headers
259   :type 'sexp)
260
261 (defcustom message-ignored-news-headers
262   "^NNTP-Posting-Host:\\|^Xref:\\|^[BGF]cc:\\|^Resent-Fcc:\\|^X-Draft-From:\\|^X-Gnus-Agent-Meta-Information:"
263   "*Regexp of headers to be removed unconditionally before posting."
264   :group 'message-news
265   :group 'message-headers
266   :type 'regexp)
267
268 (defcustom message-ignored-mail-headers
269   "^[GF]cc:\\|^Resent-Fcc:\\|^Xref:\\|^X-Draft-From:\\|^X-Gnus-Agent-Meta-Information:"
270   "*Regexp of headers to be removed unconditionally before mailing."
271   :group 'message-mail
272   :group 'message-headers
273   :type 'regexp)
274
275 (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:\\|^Cancel-Lock:\\|^Cancel-Key:"
276   "*Header lines matching this regexp will be deleted before posting.
277 It's best to delete old Path and Date headers before posting to avoid
278 any confusion."
279   :group 'message-interface
280   :type 'regexp)
281
282 (defcustom message-supersede-setup-function
283   'message-supersede-setup-for-mime-edit
284   "Function to setup a supersede message."
285   :group 'message-sending
286   :type 'function)
287
288 (defcustom message-subject-re-regexp
289   "^[ \t]*\\([Rr][Ee]\\(\\[[0-9]*\\]\\)*:[ \t]*\\)*[ \t]*"
290   "*Regexp matching \"Re: \" in the subject line."
291   :group 'message-various
292   :type 'regexp)
293
294 ;;; Some sender agents encode the whole subject including leading "Re: ".
295 ;;; And if followup agent does not decode it for some reason (e.g. unknown
296 ;;; charset) and just add a new "Re: " in front of the encoded-word, the
297 ;;; result will contain multiple "Re: "'s.
298 (defcustom message-subject-encoded-re-regexp
299   (concat
300    "^[ \t]*"
301    (regexp-quote "=?")
302    "[-!#$%&'*+0-9A-Z^_`a-z{|}~]+" ; charset
303    (regexp-quote "?")
304    "\\("
305    "[Bb]" (regexp-quote "?") ; B encoding
306    "\\(\\(CQk\\|CSA\\|IAk\\|ICA\\)[Jg]\\)*" ; \([ \t][ \t][ \t]\)*
307    "\\("
308    "[Uc][km]U6" ; [Rr][Ee]:
309    "\\|"
310    "\\(C[VX]\\|I[FH]\\)J[Fl]O[g-v]" ; [ \t][Rr][Ee]:
311    "\\|"
312    "\\(CQl\\|CSB\\|IAl\\|ICB\\)[Sy][RZ]T[o-r]" ; [ \t][ \t][Rr][Ee]:
313    "\\)"
314    "\\|"
315    "[Qb]" (regexp-quote "?") ; Q encoding
316    "\\(_\\|=09\\|=20\\)*"
317    "\\([Rr]\\|=[57]2\\)\\([Ee]\\|=[46]5\\)\\(:\\|=3[Aa]\\)"
318    "\\)"
319    )
320   "*Regexp matching \"Re: \" in the subject line.
321 Unlike `message-subject-re-regexp', this regexp matches \"Re: \" within
322 an encoded-word."
323   :group 'message-various
324   :type 'regexp)
325
326 (defcustom message-use-subject-re t
327   "*If t, remove any (buggy) \"Re: \"'s from the subject of the precursor
328 and add a new \"Re: \".  If it is nil, use the subject \"as-is\".  If it
329 is the symbol `guess', try to detect \"Re: \" within an encoded-word."
330   :group 'message-various
331   :type '(choice (const :tag "off" nil)
332                  (const :tag "on" t)
333                  (const guess)))
334
335 ;;;###autoload
336 (defcustom message-signature-separator "^-- *$"
337   "Regexp matching the signature separator."
338   :type 'regexp
339   :group 'message-various)
340
341 (defcustom message-signature-separator-for-insertion "-- \n"
342   "*Signature separator. This value will be inserted as signature separator
343 when composing message. Default value is \"-- \\n\". Notice: Changing this
344 value may go against RFC-1036 and draft-ietf-usefor-article-05.txt. "
345   :type 'string
346   :group 'message-insertion)
347
348 (defcustom message-elide-ellipsis "\n[...]\n\n"
349   "*The string which is inserted for elided text."
350   :type 'string
351   :group 'message-various)
352
353 (defcustom message-interactive nil
354   "Non-nil means when sending a message wait for and display errors.
355 nil means let mailer mail back a message to report errors."
356   :group 'message-sending
357   :group 'message-mail
358   :type 'boolean)
359
360 (defcustom message-generate-new-buffers 'unique
361   "*Non-nil means create a new message buffer whenever `message-setup' is called.
362 If this is a function, call that function with three parameters:  The type,
363 the to address and the group name.  (Any of these may be nil.)  The function
364 should return the new buffer name."
365   :group 'message-buffers
366   :type '(choice (const :tag "off" nil)
367                  (const :tag "unique" unique)
368                  (const :tag "unsent" unsent)
369                  (function fun)))
370
371 (defcustom message-kill-buffer-on-exit nil
372   "*Non-nil means that the message buffer will be killed after sending a message."
373   :group 'message-buffers
374   :type 'boolean)
375
376 (defcustom message-kill-buffer-query-function 'yes-or-no-p
377   "*Function used to prompt user whether to kill the message buffer.  If
378 it is t, the buffer will be killed unconditionally."
379   :type '(radio (function-item yes-or-no-p)
380                 (function-item y-or-n-p)
381                 (function-item nnheader-Y-or-n-p)
382                 (function :tag "Other" t))
383   :group 'message-buffers)
384
385 (defcustom message-kill-buffer-and-remove-file t
386   "*Non-nil means that the associated file will be removed before
387 removing the message buffer.  However, it is treated as nil when the
388 command `message-mimic-kill-buffer' is used."
389   :group 'message-buffers
390   :type 'boolean)
391
392 (eval-when-compile
393   (defvar gnus-local-organization))
394 (defcustom message-user-organization
395   (or (and (boundp 'gnus-local-organization)
396            (stringp gnus-local-organization)
397            gnus-local-organization)
398       (getenv "ORGANIZATION")
399       t)
400   "*String to be used as an Organization header.
401 If t, use `message-user-organization-file'."
402   :group 'message-headers
403   :type '(choice string
404                  (const :tag "consult file" t)))
405
406 ;;;###autoload
407 (defcustom message-user-organization-file "/usr/lib/news/organization"
408   "*Local news organization file."
409   :type 'file
410   :group 'message-headers)
411
412 (defcustom message-forward-start-separator
413   (concat (mime-make-tag "message" "rfc822") "\n")
414   "*Delimiter inserted before forwarded messages."
415   :group 'message-forwarding
416   :type 'string)
417
418 (defcustom message-forward-end-separator
419   (concat (mime-make-tag "text" "plain") "\n")
420   "*Delimiter inserted after forwarded messages."
421   :group 'message-forwarding
422   :type 'string)
423
424 (defcustom message-included-forward-headers
425   "^From:\\|^Newsgroups:\\|^Subject:\\|^Date:\\|^\\(Mail-\\)?Followup-To:\\|^\\(Mail-\\)?Reply-To:\\|^Mail-Copies-To:\\|^Organization:\\|^Summary:\\|^Keywords:\\|^To:\\|^Cc:\\|^Posted-To:\\|^Apparently-To:\\|^Gnus-Warning:\\|^Resent-\\|^Message-ID:\\|^References:\\|^Content-\\|^MIME-Version:"
426   "*Regexp matching headers to be included in forwarded messages."
427   :group 'message-forwarding
428   :type 'regexp)
429
430 (defcustom message-make-forward-subject-function
431   'message-forward-subject-author-subject
432   "*List of functions called to generate subject headers for forwarded messages.
433 The subject generated by the previous function is passed into each
434 successive function.
435
436 The provided functions are:
437
438 * `message-forward-subject-author-subject' (Source of article (author or
439       newsgroup)), in brackets followed by the subject
440 * `message-forward-subject-fwd' (Subject of article with 'Fwd:' prepended
441       to it."
442   :group 'message-forwarding
443   :type '(radio (function-item message-forward-subject-author-subject)
444                 (function-item message-forward-subject-fwd)
445                 (repeat :tag "List of functions" function)))
446
447 (defcustom message-forward-as-mime t
448   "*If non-nil, forward messages as an inline/rfc822 MIME section.  Otherwise, directly inline the old message in the forwarded message."
449   :version "21.1"
450   :group 'message-forwarding
451   :type 'boolean)
452
453 (defcustom message-forward-show-mml t
454   "*If non-nil, forward messages are shown as mml.  Otherwise, forward messages are unchanged."
455   :version "21.1"
456   :group 'message-forwarding
457   :type 'boolean)
458
459 (defcustom message-forward-before-signature t
460   "*If non-nil, put forwarded message before signature, else after."
461   :group 'message-forwarding
462   :type 'boolean)
463
464 (defcustom message-wash-forwarded-subjects nil
465   "*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."
466   :group 'message-forwarding
467   :type 'boolean)
468
469 (defcustom message-ignored-resent-headers "^Return-receipt\\|^X-Gnus\\|^Gnus-Warning:"
470   "*All headers that match this regexp will be deleted when resending a message."
471   :group 'message-interface
472   :type 'regexp)
473
474 (defcustom message-forward-ignored-headers "^Content-Transfer-Encoding:\\|^X-Gnus"
475   "*All headers that match this regexp will be deleted when forwarding a message."
476   :version "21.1"
477   :group 'message-forwarding
478   :type '(choice (const :tag "None" nil)
479                  regexp))
480
481 (defcustom message-ignored-cited-headers "."
482   "*Delete these headers from the messages you yank."
483   :group 'message-insertion
484   :type 'regexp)
485
486 (defcustom message-cite-prefix-regexp
487   (if (string-match "[[:digit:]]" "1") ;; support POSIX?
488       "\\([ \t]*[-_.[:word:]]+>+\\|[ \t]*[]>»|:}+]\\)+"
489     ;; ?-, ?_ or ?. MUST NOT be in syntax entry w.
490     (let ((old-table (syntax-table))
491           non-word-constituents)
492       (set-syntax-table text-mode-syntax-table)
493       (setq non-word-constituents
494             (concat
495              (if (string-match "\\w" "-")  "" "-")
496              (if (string-match "\\w" "_")  "" "_")
497              (if (string-match "\\w" ".")  "" ".")))
498       (set-syntax-table old-table)
499       (if (equal non-word-constituents "")
500           "\\([ \t]*\\(\\w\\)+>+\\|[ \t]*[]>»|:}+]\\)+"
501         (concat "\\([ \t]*\\(\\w\\|["
502                 non-word-constituents
503                 "]\\)+>+\\|[ \t]*[]>»|:}+]\\)+"))))
504   "*Regexp matching the longest possible citation prefix on a line."
505   :group 'message-insertion
506   :type 'regexp)
507
508 (defcustom message-cancel-message "I am canceling my own article.\n"
509   "Message to be inserted in the cancel message."
510   :group 'message-interface
511   :type 'string)
512
513 ;; Useful to set in site-init.el
514 ;;;###autoload
515 (defcustom message-send-mail-function 'message-send-mail-with-sendmail
516   "Function to call to send the current buffer as mail.
517 The headers should be delimited by a line whose contents match the
518 variable `mail-header-separator'.
519
520 Valid values include `message-send-mail-with-sendmail' (the default),
521 `message-send-mail-with-mh', `message-send-mail-with-qmail',
522 `message-send-mail-with-smtp', `smtpmail-send-it' and `feedmail-send-it'.
523
524 See also `send-mail-function'."
525   :type '(radio (function-item message-send-mail-with-sendmail)
526                 (function-item message-send-mail-with-mh)
527                 (function-item message-send-mail-with-qmail)
528                 (function-item message-send-mail-with-smtp)
529                 (function-item smtpmail-send-it)
530                 (function-item feedmail-send-it)
531                 (function :tag "Other"))
532   :group 'message-sending
533   :group 'message-mail)
534
535 ;; 1997-09-29 by MORIOKA Tomohiko
536 (defcustom message-send-news-function 'message-send-news-with-gnus
537   "Function to call to send the current buffer as news.
538 The headers should be delimited by a line whose contents match the
539 variable `mail-header-separator'."
540   :group 'message-sending
541   :group 'message-news
542   :type 'function)
543
544 (defcustom message-reply-to-function nil
545   "If non-nil, function that should return a list of headers.
546 This function should pick out addresses from the To, Cc, and From headers
547 and respond with new To and Cc headers."
548   :group 'message-interface
549   :type '(choice function (const nil)))
550
551 (defcustom message-wide-reply-to-function nil
552   "If non-nil, function that should return a list of headers.
553 This function should pick out addresses from the To, Cc, and From headers
554 and respond with new To and Cc headers."
555   :group 'message-interface
556   :type '(choice function (const nil)))
557
558 (defcustom message-followup-to-function nil
559   "If non-nil, function that should return a list of headers.
560 This function should pick out addresses from the To, Cc, and From headers
561 and respond with new To and Cc headers."
562   :group 'message-interface
563   :type '(choice function (const nil)))
564
565 (defcustom message-use-followup-to 'ask
566   "*Specifies what to do with Followup-To header.
567 If nil, always ignore the header.  If it is t, use its value, but
568 query before using the \"poster\" value.  If it is the symbol `ask',
569 always query the user whether to use the value.  If it is the symbol
570 `use', always use the value."
571   :group 'message-interface
572   :type '(choice (const :tag "ignore" nil)
573                  (const :tag "use & query" t)
574                  (const :tag "maybe" t)
575                  (const :tag "always" use)
576                  (const :tag "ask" ask)))
577
578 (defcustom message-use-mail-copies-to 'ask
579   "*Specifies what to do with Mail-Copies-To header.
580 If nil, always ignore the header.  If it is t, use its value, but
581 query before using the value other than \"always\" or \"never\".
582 If it is the symbol `ask', always query the user whether to use
583 the value.  If it is the symbol `use', always use the value."
584   :group 'message-interface
585   :type '(choice (const :tag "ignore" nil)
586                  (const :tag "maybe" t)
587                  (const :tag "always" use)
588                  (const :tag "ask" ask)))
589
590 ;;; XXX: 'ask and 'use are not implemented yet.
591 (defcustom message-use-mail-reply-to 'ask
592   "*Specifies what to do with Mail-Reply-To/Reply-To header.
593 If nil, always ignore the header.  If it is t or the symbol `use', use
594 its value.  If it is the symbol `ask', always query the user whether to
595 use the value.  Note that if \"Reply-To\" is marked as \"broken\", its value
596 is never used."
597   :group 'message-interface
598   :type '(choice (const :tag "ignore" nil)
599                  (const :tag "maybe" t)
600                  (const :tag "always" use)
601                  (const :tag "ask" ask)))
602
603 (defcustom message-use-mail-followup-to 'use
604   "*Specifies what to do with Mail-Followup-To header.
605 If nil, always ignore the header.  If it is the symbol `ask', always
606 query the user whether to use the value.  If it is t or the symbol
607 `use', always use the value."
608   :group 'message-interface
609   :type '(choice (const :tag "ignore" nil)
610                  (const :tag "maybe" t)
611                  (const :tag "always" use)
612                  (const :tag "ask" ask)))
613
614 (defcustom message-subscribed-address-functions nil
615   "*Specifies functions for determining list subscription.
616 If nil, do not attempt to determine list subscribtion with functions.
617 If non-nil, this variable contains a list of functions which return
618 regular expressions to match lists.  These functions can be used in
619 conjunction with `message-subscribed-regexps' and
620 `message-subscribed-addresses'."
621   :group 'message-interface
622   :type '(repeat sexp))
623
624 (defcustom message-subscribed-address-file nil
625   "*A file containing addresses the user is subscribed to.
626 If nil, do not look at any files to determine list subscriptions.  If
627 non-nil, each line of this file should be a mailing list address."
628   :group 'message-interface
629   :type 'string)
630
631 (defcustom message-subscribed-addresses nil
632   "*Specifies a list of addresses the user is subscribed to.
633 If nil, do not use any predefined list subscriptions.  This list of
634 addresses can be used in conjuction with
635 `message-subscribed-address-functions' and `message-subscribed-regexps'."
636   :group 'message-interface
637   :type '(repeat string))
638
639 (defcustom message-subscribed-regexps nil
640   "*Specifies a list of addresses the user is subscribed to.
641 If nil, do not use any predefined list subscriptions.  This list of
642 regular expressions can be used in conjuction with
643 `message-subscribed-address-functions' and `message-subscribed-addresses'."
644   :group 'message-interface
645   :type '(repeat regexp))
646
647 (defcustom message-allow-no-recipients 'ask
648   "Specifies what to do when there are no recipients other than Gcc/Fcc.
649 If it is the symbol `always', the posting is allowed.  If it is the
650 symbol `never', the posting is not allowed.  If it is the symbol
651 `ask', you are prompted."
652   :group 'message-interface
653   :type '(choice (const always)
654                  (const never)
655                  (const ask)))
656
657 (defcustom message-sendmail-f-is-evil nil
658   "*Non-nil means don't add \"-f username\" to the sendmail command line.
659 Doing so would be even more evil than leaving it out."
660   :group 'message-sending
661   :type 'boolean)
662
663 ;; qmail-related stuff
664 (defcustom message-qmail-inject-program "/var/qmail/bin/qmail-inject"
665   "Location of the qmail-inject program."
666   :group 'message-sending
667   :type 'file)
668
669 (defcustom message-qmail-inject-args nil
670   "Arguments passed to qmail-inject programs.
671 This should be a list of strings, one string for each argument.  It
672 may also be a function.
673
674 For e.g., if you wish to set the envelope sender address so that bounces
675 go to the right place or to deal with listserv's usage of that address, you
676 might set this variable to '(\"-f\" \"you@some.where\")."
677   :group 'message-sending
678   :type '(choice (function)
679                  (repeat string)))
680
681 (defvar message-cater-to-broken-inn t
682   "Non-nil means Gnus should not fold the `References' header.
683 Folding `References' makes ancient versions of INN create incorrect
684 NOV lines.")
685
686 (eval-when-compile
687   (defvar gnus-post-method)
688   (defvar gnus-select-method))
689 (defcustom message-post-method
690   (cond ((and (boundp 'gnus-post-method)
691               (listp gnus-post-method)
692               gnus-post-method)
693          gnus-post-method)
694         ((boundp 'gnus-select-method)
695          gnus-select-method)
696         (t '(nnspool "")))
697   "*Method used to post news.
698 Note that when posting from inside Gnus, for instance, this
699 variable isn't used."
700   :group 'message-news
701   :group 'message-sending
702   ;; This should be the `gnus-select-method' widget, but that might
703   ;; create a dependence to `gnus.el'.
704   :type 'sexp)
705
706 (defcustom message-generate-headers-first nil
707   "*If non-nil, generate all required headers before composing.
708 The variables `message-required-news-headers' and
709 `message-required-mail-headers' specify which headers to generate.
710
711 Note that the variable `message-deletable-headers' specifies headers which
712 are to be deleted and then re-generated before sending, so this variable
713 will not have a visible effect for those headers."
714   :group 'message-headers
715   :type 'boolean)
716
717 (defcustom message-setup-hook '(turn-on-mime-edit)
718   "Normal hook, run each time a new outgoing message is initialized.
719 The function `message-setup' runs this hook."
720   :group 'message-various
721   :type 'hook)
722
723 (defcustom message-cancel-hook nil
724   "Hook run when cancelling articles."
725   :group 'message-various
726   :type 'hook)
727
728 (defcustom message-signature-setup-hook nil
729   "Normal hook, run each time a new outgoing message is initialized.
730 It is run after the headers have been inserted and before
731 the signature is inserted."
732   :group 'message-various
733   :type 'hook)
734
735 (defcustom message-bounce-setup-hook nil
736   "Normal hook, run each time a re-sending bounced message is initialized.
737 The function `message-bounce' runs this hook."
738   :group 'message-various
739   :type 'hook)
740
741 (defcustom message-supersede-setup-hook nil
742   "Normal hook, run each time a supersede message is initialized.
743 The function `message-supersede' runs this hook."
744   :group 'message-various
745   :type 'hook)
746
747 (defcustom message-mode-hook nil
748   "Hook run in message mode buffers."
749   :group 'message-various
750   :type 'hook)
751
752 (defcustom message-header-hook '((lambda () (eword-encode-header t)))
753   "Hook run in a message mode buffer narrowed to the headers."
754   :group 'message-various
755   :type 'hook)
756
757 (defcustom message-header-setup-hook nil
758   "Hook called narrowed to the headers when setting up a message buffer."
759   :group 'message-various
760   :type 'hook)
761
762 (defcustom message-minibuffer-local-map
763   (let ((map (make-sparse-keymap 'message-minibuffer-local-map)))
764     (set-keymap-parent map minibuffer-local-map)
765     map)
766   "Keymap for `message-read-from-minibuffer'.")
767
768 ;;;###autoload
769 (defcustom message-citation-line-function 'message-insert-citation-line
770   "*Function called to insert the \"Whomever writes:\" line.
771
772 Note that Gnus provides a feature where the reader can click on
773 `writes:' to hide the cited text.  If you change this line too much,
774 people who read your message will have to change their Gnus
775 configuration.  See the variable `gnus-cite-attribution-suffix'."
776   :type 'function
777   :group 'message-insertion)
778
779 ;;;###autoload
780 (defcustom message-yank-prefix "> "
781   "*Prefix inserted on the lines of yanked messages.
782 Fix `message-cite-prefix-regexp' if it is set to an abnormal value.
783 See also `message-yank-cited-prefix'."
784   :type 'string
785   :group 'message-insertion)
786
787 (defcustom message-yank-add-new-references t
788   "Non-nil means new IDs will be added to \"References\" field when an
789 article is yanked by the command `message-yank-original' interactively.
790 If it is a symbol `message-id-only', only an ID from \"Message-ID\" field
791 is used, otherwise IDs extracted from \"References\", \"In-Reply-To\" and
792 \"Message-ID\" fields are used."
793   :type '(radio (const :tag "Do not add anything" nil)
794                 (const :tag "From Message-Id, References and In-Reply-To fields" t)
795                 (const :tag "From only Message-Id field." message-id-only))
796   :group 'message-insertion)
797
798 (defcustom message-list-references-add-position nil
799   "Integer value means position for adding to \"References\" field when
800 an article is yanked by the command `message-yank-original' interactively."
801   :type '(radio (const :tag "Add to last" nil)
802                 (integer :tag "Position from last ID"))
803   :group 'message-insertion)
804
805 (defcustom message-yank-cited-prefix ">"
806   "*Prefix inserted on cited or empty lines of yanked messages.
807 Fix `message-cite-prefix-regexp' if it is set to an abnormal value.
808 See also `message-yank-prefix'."
809   :type 'string
810   :group 'message-insertion)
811
812 (defcustom message-indentation-spaces 3
813   "*Number of spaces to insert at the beginning of each cited line.
814 Used by `message-yank-original' via `message-yank-cite'."
815   :group 'message-insertion
816   :type 'integer)
817
818 ;;;###autoload
819 (defcustom message-cite-function 'message-cite-original
820   "*Function for citing an original message.
821 Predefined functions include `message-cite-original' and
822 `message-cite-original-without-signature'.
823 Note that `message-cite-original' uses `mail-citation-hook' if that is non-nil."
824   :type '(radio (function-item message-cite-original)
825                 (function-item message-cite-original-without-signature)
826                 (function-item mu-cite-original)
827                 (function-item sc-cite-original)
828                 (function :tag "Other"))
829   :group 'message-insertion)
830
831 ;;;###autoload
832 (defcustom message-suspend-font-lock-when-citing nil
833   "Non-nil means suspend font-lock'ing while citing an original message.
834 Some lazy demand-driven fontification tools (or Emacs itself) have a
835 bug that they often miss a buffer to be fontified.  It will mostly
836 occur when Emacs prompts user for any inputs in the minibuffer.
837 Setting this option to non-nil may help you to avoid unpleasant errors
838 even if it is an add-hoc expedient."
839   :type 'boolean
840   :group 'message-insertion)
841
842 ;;;###autoload
843 (defcustom message-indent-citation-function 'message-indent-citation
844   "*Function for modifying a citation just inserted in the mail buffer.
845 This can also be a list of functions.  Each function can find the
846 citation between (point) and (mark t).  And each function should leave
847 point and mark around the citation text as modified."
848   :type 'function
849   :group 'message-insertion)
850
851 ;;;###autoload
852 (defcustom message-signature t
853   "*String to be inserted at the end of the message buffer.
854 If t, the `message-signature-file' file will be inserted instead.
855 If a function, the result from the function will be used instead.
856 If a form, the result from the form will be used instead."
857   :type 'sexp
858   :group 'message-insertion)
859
860 ;;;###autoload
861 (defcustom message-signature-file "~/.signature"
862   "*Name of file containing the text inserted at end of message buffer.
863 Ignored if the named file doesn't exist.
864 If nil, don't insert a signature."
865   :type '(choice file (const :tags "None" nil))
866   :group 'message-insertion)
867
868 (defcustom message-distribution-function nil
869   "*Function called to return a Distribution header."
870   :group 'message-news
871   :group 'message-headers
872   :type '(choice function (const nil)))
873
874 (defcustom message-expires 14
875   "Number of days before your article expires."
876   :group 'message-news
877   :group 'message-headers
878   :link '(custom-manual "(message)News Headers")
879   :type 'integer)
880
881 (defcustom message-user-path nil
882   "If nil, use the NNTP server name in the Path header.
883 If stringp, use this; if non-nil, use no host name (user name only)."
884   :group 'message-news
885   :group 'message-headers
886   :link '(custom-manual "(message)News Headers")
887   :type '(choice (const :tag "nntp" nil)
888                  (string :tag "name")
889                  (sexp :tag "none" :format "%t" t)))
890
891 (defvar message-reply-buffer nil)
892 (defvar message-reply-headers nil
893   "The headers of the current replied article.
894 It is a vector of the following headers:
895 \[number subject from date id references chars lines xref extra].")
896 (defvar message-sent-message-via nil)
897 (defvar message-checksum nil)
898 (defvar message-send-actions nil
899   "A list of actions to be performed upon successful sending of a message.")
900 (defvar message-exit-actions nil
901   "A list of actions to be performed upon exiting after sending a message.")
902 (defvar message-kill-actions nil
903   "A list of actions to be performed before killing a message buffer.")
904 (defvar message-postpone-actions nil
905   "A list of actions to be performed after postponing a message.")
906 (defvar message-original-frame nil)
907 (defvar message-parameter-alist nil)
908 (defvar message-startup-parameter-alist nil)
909
910 (define-widget 'message-header-lines 'text
911   "All header lines must be LFD terminated."
912   :format "%{%t%}:%n%v"
913   :valid-regexp "^\\'"
914   :error "All header lines must be newline terminated")
915
916 (defcustom message-default-headers ""
917   "*A string containing header lines to be inserted in outgoing messages.
918 It is inserted before you edit the message, so you can edit or delete
919 these lines."
920   :group 'message-headers
921   :type 'message-header-lines)
922
923 (defcustom message-default-mail-headers ""
924   "*A string of header lines to be inserted in outgoing mails."
925   :group 'message-headers
926   :group 'message-mail
927   :type 'message-header-lines)
928
929 (defcustom message-default-news-headers ""
930   "*A string of header lines to be inserted in outgoing news articles."
931   :group 'message-headers
932   :group 'message-news
933   :type 'message-header-lines)
934
935 ;; Note: could use /usr/ucb/mail instead of sendmail;
936 ;; options -t, and -v if not interactive.
937 (defcustom message-mailer-swallows-blank-line
938   (if (and (string-match "sparc-sun-sunos\\(\\'\\|[^5]\\)"
939                          system-configuration)
940            (file-readable-p "/etc/sendmail.cf")
941            (let ((buffer (get-buffer-create " *temp*")))
942              (unwind-protect
943                  (save-excursion
944                    (set-buffer buffer)
945                    (insert-file-contents "/etc/sendmail.cf")
946                    (goto-char (point-min))
947                    (let ((case-fold-search nil))
948                      (re-search-forward "^OR\\>" nil t)))
949                (kill-buffer buffer))))
950       ;; According to RFC822, "The field-name must be composed of printable
951       ;; ASCII characters (i. e., characters that have decimal values between
952       ;; 33 and 126, except colon)", i. e., any chars except ctl chars,
953       ;; space, or colon.
954       '(looking-at "[ \t]\\|[][!\"#$%&'()*+,-./0-9;<=>?@A-Z\\\\^_`a-z{|}~]+:"))
955   "*Set this non-nil if the system's mailer runs the header and body together.
956 \(This problem exists on Sunos 4 when sendmail is run in remote mode.)
957 The value should be an expression to test whether the problem will
958 actually occur."
959   :group 'message-sending
960   :type 'sexp)
961
962 ;;; XXX: This symbol is overloaded!  See below.
963 (defvar message-user-agent nil
964   "String of the form of PRODUCT/VERSION.  Used for User-Agent header field.")
965
966 (static-when (boundp 'MULE)
967   (require 'reporter));; `define-mail-user-agent' is here.
968
969 ;;;###autoload
970 (define-mail-user-agent 'message-user-agent
971   'message-mail 'message-send-and-exit
972   'message-kill-buffer 'message-send-hook)
973
974 (defvar message-mh-deletable-headers '(Message-ID Date Lines Sender)
975   "If non-nil, delete the deletable headers before feeding to mh.")
976
977 (defvar message-send-method-alist
978   '((news message-news-p message-send-via-news)
979     (mail message-mail-p message-send-via-mail))
980   "Alist of ways to send outgoing messages.
981 Each element has the form
982
983   \(TYPE PREDICATE FUNCTION)
984
985 where TYPE is a symbol that names the method; PREDICATE is a function
986 called without any parameters to determine whether the message is
987 a message of type TYPE; and FUNCTION is a function to be called if
988 PREDICATE returns non-nil.  FUNCTION is called with one parameter --
989 the prefix.")
990
991 (defcustom message-mail-alias-type 'abbrev
992   "*What alias expansion type to use in Message buffers.
993 The default is `abbrev', which uses mailabbrev.  nil switches
994 mail aliases off."
995   :group 'message
996   :link '(custom-manual "(message)Mail Aliases")
997   :type '(choice (const :tag "Use Mailabbrev" abbrev)
998                  (const :tag "No expansion" nil)))
999
1000 (defcustom message-auto-save-directory
1001   (file-name-as-directory (nnheader-concat message-directory "drafts"))
1002   "*Directory where Message auto-saves buffers if Gnus isn't running.
1003 If nil, Message won't auto-save."
1004   :group 'message-buffers
1005   :type '(choice directory (const :tag "Don't auto-save" nil)))
1006
1007 (defcustom message-buffer-naming-style 'unique
1008   "*The way new message buffers are named.
1009 Valid valued are `unique' and `unsent'."
1010   :version "21.1"
1011   :group 'message-buffers
1012   :type '(choice (const :tag "unique" unique)
1013                  (const :tag "unsent" unsent)))
1014
1015 (defcustom message-default-charset
1016   (and (featurep 'xemacs) (not (featurep 'mule)) 'iso-8859-1)
1017   "Default charset used in non-MULE XEmacsen."
1018   :version "21.1"
1019   :group 'message
1020   :type 'symbol)
1021
1022 (defcustom message-dont-reply-to-names
1023   (and (boundp 'rmail-dont-reply-to-names) rmail-dont-reply-to-names)
1024   "*A regexp specifying addresses to prune when doing wide replies.
1025 A value of nil means exclude your own user name only."
1026   :version "21.1"
1027   :group 'message
1028   :type '(choice (const :tag "Yourself" nil)
1029                  regexp))
1030
1031 (defvar message-shoot-gnksa-feet nil
1032   "*A list of GNKSA feet you are allowed to shoot.
1033 Gnus gives you all the opportunity you could possibly want for
1034 shooting yourself in the foot.  Also, Gnus allows you to shoot the
1035 feet of Good Net-Keeping Seal of Approval. The following are foot
1036 candidates:
1037 `empty-article'     Allow you to post an empty article;
1038 `quoted-text-only'  Allow you to post quoted text only;
1039 `multiple-copies'   Allow you to post multiple copies;
1040 `cancel-messages'   Allow you to cancel or supersede messages from 
1041                     your other email addresses.")
1042
1043 (defsubst message-gnksa-enable-p (feature)
1044   (or (not (listp message-shoot-gnksa-feet))
1045       (memq feature message-shoot-gnksa-feet)))
1046
1047 ;;; Internal variables.
1048 ;;; Well, not really internal.
1049
1050 (defvar message-mode-syntax-table
1051   (let ((table (copy-syntax-table text-mode-syntax-table)))
1052     (modify-syntax-entry ?% ". " table)
1053     (modify-syntax-entry ?> ". " table)
1054     (modify-syntax-entry ?< ". " table)
1055     table)
1056   "Syntax table used while in Message mode.")
1057
1058 (defface message-header-to-face
1059   '((((class color)
1060       (background dark))
1061      (:foreground "green2" :bold t))
1062     (((class color)
1063       (background light))
1064      (:foreground "MidnightBlue" :bold t))
1065     (t
1066      (:bold t :italic t)))
1067   "Face used for displaying From headers."
1068   :group 'message-faces)
1069
1070 (defface message-header-cc-face
1071   '((((class color)
1072       (background dark))
1073      (:foreground "green4" :bold t))
1074     (((class color)
1075       (background light))
1076      (:foreground "MidnightBlue"))
1077     (t
1078      (:bold t)))
1079   "Face used for displaying Cc headers."
1080   :group 'message-faces)
1081
1082 (defface message-header-subject-face
1083   '((((class color)
1084       (background dark))
1085      (:foreground "green3"))
1086     (((class color)
1087       (background light))
1088      (:foreground "navy blue" :bold t))
1089     (t
1090      (:bold t)))
1091   "Face used for displaying subject headers."
1092   :group 'message-faces)
1093
1094 (defface message-header-newsgroups-face
1095   '((((class color)
1096       (background dark))
1097      (:foreground "yellow" :bold t :italic t))
1098     (((class color)
1099       (background light))
1100      (:foreground "blue4" :bold t :italic t))
1101     (t
1102      (:bold t :italic t)))
1103   "Face used for displaying newsgroups headers."
1104   :group 'message-faces)
1105
1106 (defface message-header-other-face
1107   '((((class color)
1108       (background dark))
1109      (:foreground "#b00000"))
1110     (((class color)
1111       (background light))
1112      (:foreground "steel blue"))
1113     (t
1114      (:bold t :italic t)))
1115   "Face used for displaying newsgroups headers."
1116   :group 'message-faces)
1117
1118 (defface message-header-name-face
1119   '((((class color)
1120       (background dark))
1121      (:foreground "DarkGreen"))
1122     (((class color)
1123       (background light))
1124      (:foreground "cornflower blue"))
1125     (t
1126      (:bold t)))
1127   "Face used for displaying header names."
1128   :group 'message-faces)
1129
1130 (defface message-header-xheader-face
1131   '((((class color)
1132       (background dark))
1133      (:foreground "blue"))
1134     (((class color)
1135       (background light))
1136      (:foreground "blue"))
1137     (t
1138      (:bold t)))
1139   "Face used for displaying X-Header headers."
1140   :group 'message-faces)
1141
1142 (defface message-separator-face
1143   '((((class color)
1144       (background dark))
1145      (:foreground "blue3"))
1146     (((class color)
1147       (background light))
1148      (:foreground "brown"))
1149     (t
1150      (:bold t)))
1151   "Face used for displaying the separator."
1152   :group 'message-faces)
1153
1154 (defface message-cited-text-face
1155   '((((class color)
1156       (background dark))
1157      (:foreground "red"))
1158     (((class color)
1159       (background light))
1160      (:foreground "red"))
1161     (t
1162      (:bold t)))
1163   "Face used for displaying cited text names."
1164   :group 'message-faces)
1165
1166 (defface message-mml-face
1167   '((((class color)
1168       (background dark))
1169      (:foreground "ForestGreen"))
1170     (((class color)
1171       (background light))
1172      (:foreground "ForestGreen"))
1173     (t
1174      (:bold t)))
1175   "Face used for displaying MML."
1176   :group 'message-faces)
1177
1178 (defvar message-font-lock-keywords
1179   (let ((content "[ \t]*\\(.+\\(\n[ \t].*\\)*\\)\n?"))
1180     `((,(concat "^\\([Tt]o:\\)" content)
1181        (1 'message-header-name-face)
1182        (2 'message-header-to-face nil t))
1183       (,(concat "^\\([GBF]?[Cc][Cc]:\\|[Rr]eply-[Tt]o:\\|"
1184                 "[Mm]ail-[Cc]opies-[Tt]o:\\|"
1185                 "[Mm]ail-[Rr]eply-[Tt]o:\\|"
1186                 "[Mm]ail-[Ff]ollowup-[Tt]o:\\)" content)
1187        (1 'message-header-name-face)
1188        (2 'message-header-cc-face nil t))
1189       (,(concat "^\\([Ss]ubject:\\)" content)
1190        (1 'message-header-name-face)
1191        (2 'message-header-subject-face nil t))
1192       (,(concat "^\\([Nn]ewsgroups:\\|Followup-[Tt]o:\\)" content)
1193        (1 'message-header-name-face)
1194        (2 'message-header-newsgroups-face nil t))
1195       (,(concat "^\\([A-Z][^: \n\t]+:\\)" content)
1196        (1 'message-header-name-face)
1197        (2 'message-header-other-face nil t))
1198       (,(concat "^\\(X-[A-Za-z0-9-]+\\|In-Reply-To\\):" content)
1199        (1 'message-header-name-face)
1200        (2 'message-header-name-face))
1201       ,@(if (and mail-header-separator
1202                  (not (equal mail-header-separator "")))
1203             `((,(concat "^\\(" (regexp-quote mail-header-separator) "\\)$")
1204                1 'message-separator-face))
1205           nil)
1206       (,(concat "^\\(" message-cite-prefix-regexp "\\).*")
1207        (0 'message-cited-text-face))
1208       (,mime-edit-tag-regexp
1209        (0 'message-mml-face))))
1210   "Additional expressions to highlight in Message mode.")
1211
1212 ;; XEmacs does it like this.  For Emacs, we have to set the
1213 ;; `font-lock-defaults' buffer-local variable.
1214 (put 'message-mode 'font-lock-defaults '(message-font-lock-keywords t))
1215
1216 (defvar message-face-alist
1217   '((bold . bold-region)
1218     (underline . underline-region)
1219     (default . (lambda (b e)
1220                  (unbold-region b e)
1221                  (ununderline-region b e))))
1222   "Alist of mail and news faces for facemenu.
1223 The cdr of ech entry is a function for applying the face to a region.")
1224
1225 (defcustom message-send-hook nil
1226   "Hook run before sending messages."
1227   :group 'message-various
1228   :options '(ispell-message)
1229   :type 'hook)
1230
1231 (defcustom message-send-mail-hook nil
1232   "Hook run before sending mail messages."
1233   :group 'message-various
1234   :type 'hook)
1235
1236 (defcustom message-send-news-hook nil
1237   "Hook run before sending news messages."
1238   :group 'message-various
1239   :type 'hook)
1240
1241 (defcustom message-sent-hook nil
1242   "Hook run after sending messages."
1243   :group 'message-various
1244   :type 'hook)
1245
1246 (defcustom message-use-multi-frames nil
1247   "Make new frame when sending messages."
1248   :group 'message-frames
1249   :type 'boolean)
1250
1251 (defcustom message-delete-frame-on-exit nil
1252   "Delete frame after sending messages."
1253   :group 'message-frames
1254   :type '(choice (const :tag "off" nil)
1255                  (const :tag "always" t)
1256                  (const :tag "ask" ask)))
1257
1258 (defvar message-draft-coding-system
1259   (cond
1260    ((boundp 'MULE) '*junet*)
1261    ((not (fboundp 'find-coding-system)) nil)
1262    ((find-coding-system 'emacs-mule)
1263     (if (memq system-type '(windows-nt ms-dos ms-windows))
1264         'emacs-mule-dos 'emacs-mule))
1265    ((find-coding-system 'escape-quoted) 'escape-quoted)
1266    ((find-coding-system 'no-conversion) 'no-conversion)
1267    (t nil))
1268   "Coding system to compose mail.")
1269
1270 (defcustom message-send-mail-partially-limit 1000000
1271   "The limitation of messages sent as message/partial.
1272 The lower bound of message size in characters, beyond which the message
1273 should be sent in several parts.  If it is nil, the size is unlimited."
1274   :version "21.1"
1275   :group 'message-buffers
1276   :type '(choice (const :tag "unlimited" nil)
1277                  (integer 1000000)))
1278
1279 (defcustom message-alternative-emails nil
1280   "A regexp to match the alternative email addresses.
1281 The first matched address (not primary one) is used in the From field."
1282   :group 'message-headers
1283   :type '(choice (const :tag "Always use primary" nil)
1284                  regexp))
1285
1286 (defcustom message-hierarchical-addresses nil
1287   "A list of hierarchical mail address definitions.
1288
1289 Inside each entry, the first address is the \"top\" address, and
1290 subsequent addresses are subaddresses; this is used to indicate that
1291 mail sent to the first address will automatically be delivered to the
1292 subaddresses.  So if the first address appears in the recipient list
1293 for a message, the subaddresses will be removed (if present) before
1294 the mail is sent.  All addresses in this structure should be
1295 downcased."
1296   :group 'message-headers
1297   :type '(repeat (repeat string)))
1298
1299 (defcustom message-mail-user-agent nil
1300   "Like `mail-user-agent'.
1301 Except if it is nil, use Gnus native MUA; if it is t, use
1302 `mail-user-agent'."
1303   :type '(radio (const :tag "Gnus native"
1304                        :format "%t\n"
1305                        nil)
1306                 (const :tag "`mail-user-agent'"
1307                        :format "%t\n"
1308                        t)
1309                 (function-item :tag "Default Emacs mail"
1310                                :format "%t\n"
1311                                sendmail-user-agent)
1312                 (function-item :tag "Emacs interface to MH"
1313                                :format "%t\n"
1314                                mh-e-user-agent)
1315                 (function :tag "Other"))
1316   :version "21.1"
1317   :group 'message)
1318
1319 (defcustom message-wide-reply-confirm-recipients nil
1320   "Whether to confirm a wide reply to multiple email recipients.
1321 If this variable is nil, don't ask whether to reply to all recipients.
1322 If this variable is non-nil, pose the question \"Reply to all
1323 recipients?\" before a wide reply to multiple recipients.  If the user
1324 answers yes, reply to all recipients as usual.  If the user answers
1325 no, only reply back to the author."
1326   :version "21.3"
1327   :group 'message-headers
1328   :type 'boolean)
1329
1330 ;;; Internal variables.
1331
1332 (defvar message-sending-message "Sending...")
1333 (defvar message-buffer-list nil)
1334 (defvar message-this-is-news nil)
1335 (defvar message-this-is-mail nil)
1336 (defvar message-draft-article nil)
1337 (defvar message-mime-part nil)
1338 (defvar message-posting-charset nil)
1339
1340 ;; Byte-compiler warning
1341 (eval-when-compile
1342   (defvar gnus-active-hashtb)
1343   (defvar gnus-read-active-file))
1344
1345 ;;; Regexp matching the delimiter of messages in UNIX mail format
1346 ;;; (UNIX From lines), minus the initial ^.  It should be a copy
1347 ;;; of rmail.el's rmail-unix-mail-delimiter.
1348 (defvar message-unix-mail-delimiter
1349   (let ((time-zone-regexp
1350          (concat "\\([A-Z]?[A-Z]?[A-Z][A-Z]\\( DST\\)?"
1351                  "\\|[-+]?[0-9][0-9][0-9][0-9]"
1352                  "\\|"
1353                  "\\) *")))
1354     (concat
1355      "From "
1356
1357      ;; Many things can happen to an RFC 822 mailbox before it is put into
1358      ;; a `From' line.  The leading phrase can be stripped, e.g.
1359      ;; `Joe <@w.x:joe@y.z>' -> `<@w.x:joe@y.z>'.  The <> can be stripped, e.g.
1360      ;; `<@x.y:joe@y.z>' -> `@x.y:joe@y.z'.  Everything starting with a CRLF
1361      ;; can be removed, e.g.
1362      ;;         From: joe@y.z (Joe      K
1363      ;;                 User)
1364      ;; can yield `From joe@y.z (Joe    K Fri Mar 22 08:11:15 1996', and
1365      ;;         From: Joe User
1366      ;;                 <joe@y.z>
1367      ;; can yield `From Joe User Fri Mar 22 08:11:15 1996'.
1368      ;; The mailbox can be removed or be replaced by white space, e.g.
1369      ;;         From: "Joe User"{space}{tab}
1370      ;;                 <joe@y.z>
1371      ;; can yield `From {space}{tab} Fri Mar 22 08:11:15 1996',
1372      ;; where {space} and {tab} represent the Ascii space and tab characters.
1373      ;; We want to match the results of any of these manglings.
1374      ;; The following regexp rejects names whose first characters are
1375      ;; obviously bogus, but after that anything goes.
1376      "\\([^\0-\b\n-\r\^?].*\\)? "
1377
1378      ;; The time the message was sent.
1379      "\\([^\0-\r \^?]+\\) +"            ; day of the week
1380      "\\([^\0-\r \^?]+\\) +"            ; month
1381      "\\([0-3]?[0-9]\\) +"              ; day of month
1382      "\\([0-2][0-9]:[0-5][0-9]\\(:[0-6][0-9]\\)?\\) *" ; time of day
1383
1384      ;; Perhaps a time zone, specified by an abbreviation, or by a
1385      ;; numeric offset.
1386      time-zone-regexp
1387
1388      ;; The year.
1389      " \\([0-9][0-9]+\\) *"
1390
1391      ;; On some systems the time zone can appear after the year, too.
1392      time-zone-regexp
1393
1394      ;; Old uucp cruft.
1395      "\\(remote from .*\\)?"
1396
1397      "\n"))
1398   "Regexp matching the delimiter of messages in UNIX mail format.")
1399
1400 (defvar message-unsent-separator
1401   (concat "^ *---+ +Unsent message follows +---+ *$\\|"
1402           "^ *---+ +Returned message +---+ *$\\|"
1403           "^Start of returned message$\\|"
1404           "^ *---+ +Original message +---+ *$\\|"
1405           "^ *--+ +begin message +--+ *$\\|"
1406           "^ *---+ +Original message follows +---+ *$\\|"
1407           "^ *---+ +Undelivered message follows +---+ *$\\|"
1408           "^|? *---+ +Message text follows: +---+ *|?$")
1409   "A regexp that matches the separator before the text of a failed message.")
1410
1411 (defvar message-header-format-alist
1412   `((Newsgroups)
1413     (To . message-fill-address)
1414     (Cc . message-fill-address)
1415     (Subject)
1416     (In-Reply-To)
1417     (Fcc)
1418     (Bcc)
1419     (Date)
1420     (Organization)
1421     (Distribution)
1422     (Lines)
1423     (Expires)
1424     (Message-ID)
1425     (References . message-shorten-references)
1426     (User-Agent))
1427   "Alist used for formatting headers.")
1428
1429 (defvar message-options nil
1430   "Some saved answers when sending message.")
1431
1432 (defvar message-send-mail-real-function nil
1433   "Internal send mail function.")
1434
1435 (defvar message-bogus-system-names "^localhost\\."
1436   "The regexp of bogus system names.")
1437
1438 (eval-and-compile
1439   (autoload 'message-setup-toolbar "messagexmas")
1440   (autoload 'mh-new-draft-name "mh-comp")
1441   (autoload 'mh-send-letter "mh-comp")
1442   (autoload 'gnus-point-at-eol "gnus-util")
1443   (autoload 'gnus-point-at-bol "gnus-util")
1444   (autoload 'gnus-output-to-rmail "gnus-util")
1445   (autoload 'gnus-output-to-mail "gnus-util")
1446   (autoload 'nndraft-request-associate-buffer "nndraft")
1447   (autoload 'nndraft-request-expire-articles "nndraft")
1448   (autoload 'gnus-open-server "gnus-int")
1449   (autoload 'gnus-request-post "gnus-int")
1450   (autoload 'gnus-copy-article-buffer "gnus-msg")
1451   (autoload 'gnus-alive-p "gnus-util")
1452   (autoload 'gnus-server-string "gnus")
1453   (autoload 'gnus-group-name-charset "gnus-group")
1454   (autoload 'gnus-group-name-decode "gnus-group")
1455   (autoload 'gnus-groups-from-server "gnus")
1456   (autoload 'rmail-output "rmailout")
1457   (autoload 'mu-cite-original "mu-cite"))
1458
1459 \f
1460
1461 ;;;
1462 ;;; Utility functions.
1463 ;;;
1464 (defun message-eval-parameter (parameter)
1465   (condition-case ()
1466       (if (symbolp parameter)
1467           (if (functionp parameter)
1468               (funcall parameter)
1469             (eval parameter))
1470         parameter)
1471     (error nil)))
1472
1473 (defsubst message-get-parameter (key &optional alist)
1474   (unless alist
1475     (setq alist message-parameter-alist))
1476   (cdr (assq key alist)))
1477
1478 (defmacro message-get-parameter-with-eval (key &optional alist)
1479   `(message-eval-parameter (message-get-parameter ,key ,alist)))
1480
1481 (defmacro message-y-or-n-p (question show &rest text)
1482   "Ask QUESTION, displaying remaining args in a temporary buffer if SHOW."
1483   `(message-talkative-question 'y-or-n-p ,question ,show ,@text))
1484
1485 (defmacro message-delete-line (&optional n)
1486   "Delete the current line (and the next N lines)."
1487   `(delete-region (progn (beginning-of-line) (point))
1488                   (progn (forward-line ,(or n 1)) (point))))
1489
1490 (defun message-unquote-tokens (elems)
1491   "Remove double quotes (\") from strings in list ELEMS."
1492   (mapcar (lambda (item)
1493             (while (string-match "^\\(.*\\)\"\\(.*\\)$" item)
1494               (setq item (concat (match-string 1 item)
1495                                  (match-string 2 item))))
1496             item)
1497           elems))
1498
1499 (defun message-tokenize-header (header &optional separator)
1500   "Split HEADER into a list of header elements.
1501 SEPARATOR is a string of characters to be used as separators.  \",\"
1502 is used by default."
1503   (if (not header)
1504       nil
1505     (let ((regexp (format "[%s]+" (or separator ",")))
1506           (beg 1)
1507           (first t)
1508           quoted elems paren)
1509       (save-excursion
1510         (message-set-work-buffer)
1511         (insert header)
1512         (goto-char (point-min))
1513         (while (not (eobp))
1514           (if first
1515               (setq first nil)
1516             (forward-char 1))
1517           (cond ((and (> (point) beg)
1518                       (or (eobp)
1519                           (and (looking-at regexp)
1520                                (not quoted)
1521                                (not paren))))
1522                  (push (buffer-substring beg (point)) elems)
1523                  (setq beg (match-end 0)))
1524                 ((eq (char-after) ?\")
1525                  (setq quoted (not quoted)))
1526                 ((and (eq (char-after) ?\()
1527                       (not quoted))
1528                  (setq paren t))
1529                 ((and (eq (char-after) ?\))
1530                       (not quoted))
1531                  (setq paren nil))))
1532         (nreverse elems)))))
1533
1534 (defun message-mail-file-mbox-p (file)
1535   "Say whether FILE looks like a Unix mbox file."
1536   (when (and (file-exists-p file)
1537              (file-readable-p file)
1538              (file-regular-p file))
1539     (with-temp-buffer
1540       (nnheader-insert-file-contents file)
1541       (goto-char (point-min))
1542       (looking-at message-unix-mail-delimiter))))
1543
1544 (defun message-fetch-field (header &optional not-all)
1545   "The same as `mail-fetch-field', only remove all newlines."
1546   (let* ((inhibit-point-motion-hooks t)
1547          (case-fold-search t)
1548          (value (mail-fetch-field header nil (not not-all))))
1549     (when value
1550       (while (string-match "\n[\t ]+" value)
1551         (setq value (replace-match " " t t value)))
1552       (set-text-properties 0 (length value) nil value)
1553       value)))
1554
1555 (defun message-narrow-to-field ()
1556   "Narrow the buffer to the header on the current line."
1557   (beginning-of-line)
1558   (narrow-to-region
1559    (point)
1560    (progn
1561      (forward-line 1)
1562      (if (re-search-forward "^[^ \n\t]" nil t)
1563          (progn
1564            (beginning-of-line)
1565            (point))
1566        (point-max))))
1567   (goto-char (point-min)))
1568
1569 (defun message-add-header (&rest headers)
1570   "Add the HEADERS to the message header, skipping those already present."
1571   (while headers
1572     (let (hclean)
1573       (unless (string-match "^\\([^:]+\\):[ \t]*[^ \t]" (car headers))
1574         (error "Invalid header `%s'" (car headers)))
1575       (setq hclean (match-string 1 (car headers)))
1576       (save-restriction
1577         (message-narrow-to-headers)
1578         (unless (re-search-forward (concat "^" (regexp-quote hclean) ":") nil t)
1579           (goto-char (point-max))
1580           (if (string-match "\n$" (car headers))
1581               (insert (car headers))
1582             (insert (car headers) ?\n)))))
1583     (setq headers (cdr headers))))
1584
1585
1586 (defun message-fetch-reply-field (header)
1587   "Fetch field HEADER from the message we're replying to."
1588   (let ((buffer (message-eval-parameter message-reply-buffer)))
1589     (when (and buffer
1590                (buffer-name buffer))
1591       (save-excursion
1592         (set-buffer buffer)
1593         (message-fetch-field header)))))
1594
1595 (defun message-set-work-buffer ()
1596   (if (get-buffer " *message work*")
1597       (progn
1598         (set-buffer " *message work*")
1599         (erase-buffer))
1600     (set-buffer (get-buffer-create " *message work*"))
1601     (kill-all-local-variables)))
1602
1603 (defun message-functionp (form)
1604   "Return non-nil if FORM is funcallable."
1605   (or (and (symbolp form) (fboundp form))
1606       (and (listp form) (eq (car form) 'lambda))
1607       (byte-code-function-p form)))
1608
1609 (defun message-strip-list-identifiers (subject)
1610   "Remove list identifiers in `gnus-list-identifiers' from string SUBJECT."
1611   (require 'gnus-sum)                   ; for gnus-list-identifiers
1612   (let ((regexp (if (stringp gnus-list-identifiers)
1613                     gnus-list-identifiers
1614                   (mapconcat 'identity gnus-list-identifiers " *\\|"))))
1615     (if (string-match (concat "\\(\\(\\(Re: +\\)?\\(" regexp
1616                               " *\\)\\)+\\(Re: +\\)?\\)") subject)
1617         (concat (substring subject 0 (match-beginning 1))
1618                 (or (match-string 3 subject)
1619                     (match-string 5 subject))
1620                 (substring subject
1621                            (match-end 1)))
1622       subject)))
1623
1624 (defun message-strip-subject-re (subject)
1625   "Remove \"Re:\" from subject lines in string SUBJECT."
1626   (if (string-match message-subject-re-regexp subject)
1627       (substring subject (match-end 0))
1628     subject))
1629
1630 (defun message-remove-header (header &optional is-regexp first reverse)
1631   "Remove HEADER in the narrowed buffer.
1632 If IS-REGEXP, HEADER is a regular expression.
1633 If FIRST, only remove the first instance of the header.
1634 Return the number of headers removed."
1635   (goto-char (point-min))
1636   (let ((regexp (if is-regexp header (concat "^" (regexp-quote header) ":")))
1637         (number 0)
1638         (case-fold-search t)
1639         last)
1640     (while (and (not (eobp))
1641                 (not last))
1642       (if (if reverse
1643               (not (looking-at regexp))
1644             (looking-at regexp))
1645           (progn
1646             (incf number)
1647             (when first
1648               (setq last t))
1649             (delete-region
1650              (point)
1651              ;; There might be a continuation header, so we have to search
1652              ;; until we find a new non-continuation line.
1653              (progn
1654                (forward-line 1)
1655                (if (re-search-forward "^[^ \t]" nil t)
1656                    (goto-char (match-beginning 0))
1657                  (point-max)))))
1658         (forward-line 1)
1659         (if (re-search-forward "^[^ \t]" nil t)
1660             (goto-char (match-beginning 0))
1661           (goto-char (point-max)))))
1662     number))
1663
1664 (defun message-remove-first-header (header)
1665   "Remove the first instance of HEADER if there is more than one."
1666   (let ((count 0)
1667         (regexp (concat "^" (regexp-quote header) ":")))
1668     (save-excursion
1669       (goto-char (point-min))
1670       (while (re-search-forward regexp nil t)
1671         (incf count)))
1672     (while (> count 1)
1673       (message-remove-header header nil t)
1674       (decf count))))
1675
1676 (defun message-narrow-to-headers ()
1677   "Narrow the buffer to the head of the message."
1678   (widen)
1679   (narrow-to-region
1680    (goto-char (point-min))
1681    (if (re-search-forward
1682         (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
1683        (match-beginning 0)
1684      (point-max)))
1685   (goto-char (point-min)))
1686
1687 (defun message-narrow-to-head-1 ()
1688   "Like `message-narrow-to-head'.  Don't widen."
1689   (narrow-to-region
1690    (goto-char (point-min))
1691    (if (search-forward "\n\n" nil 1)
1692        (1- (point))
1693      (point-max)))
1694   (goto-char (point-min)))
1695
1696 (defun message-narrow-to-head ()
1697   "Narrow the buffer to the head of the message.
1698 Point is left at the beginning of the narrowed-to region."
1699   (widen)
1700   (message-narrow-to-head-1))
1701
1702 (defun message-narrow-to-headers-or-head ()
1703   "Narrow the buffer to the head of the message."
1704   (widen)
1705   (narrow-to-region
1706    (goto-char (point-min))
1707    (cond
1708     ((re-search-forward
1709       (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
1710      (match-beginning 0))
1711     ((search-forward "\n\n" nil t)
1712      (1- (point)))
1713     (t
1714      (point-max))))
1715   (goto-char (point-min)))
1716
1717 (defun message-news-p ()
1718   "Say whether the current buffer contains a news message."
1719   (and (not message-this-is-mail)
1720        (or message-this-is-news
1721            (save-excursion
1722              (save-restriction
1723                (message-narrow-to-headers)
1724                (and (message-fetch-field "newsgroups")
1725                     (not (message-fetch-field "posted-to"))))))))
1726
1727 (defun message-mail-p ()
1728   "Say whether the current buffer contains a mail message."
1729   (and (not message-this-is-news)
1730        (or message-this-is-mail
1731            (save-excursion
1732              (save-restriction
1733                (message-narrow-to-headers)
1734                (or (message-fetch-field "to")
1735                    (message-fetch-field "cc")
1736                    (message-fetch-field "bcc")))))))
1737
1738 (defun message-next-header ()
1739   "Go to the beginning of the next header."
1740   (beginning-of-line)
1741   (or (eobp) (forward-char 1))
1742   (not (if (re-search-forward "^[^ \t]" nil t)
1743            (beginning-of-line)
1744          (goto-char (point-max)))))
1745
1746 (defun message-sort-headers-1 ()
1747   "Sort the buffer as headers using `message-rank' text props."
1748   (goto-char (point-min))
1749   (require 'sort)
1750   (sort-subr
1751    nil 'message-next-header
1752    (lambda ()
1753      (message-next-header)
1754      (unless (bobp)
1755        (forward-char -1)))
1756    (lambda ()
1757      (or (get-text-property (point) 'message-rank)
1758          10000))))
1759
1760 (defun message-sort-headers ()
1761   "Sort the headers of the current message according to `message-header-format-alist'."
1762   (interactive)
1763   (save-excursion
1764     (save-restriction
1765       (let ((max (1+ (length message-header-format-alist)))
1766             rank)
1767         (message-narrow-to-headers)
1768         (while (re-search-forward "^[^ \n]+:" nil t)
1769           (put-text-property
1770            (match-beginning 0) (1+ (match-beginning 0))
1771            'message-rank
1772            (if (setq rank (length (memq (assq (intern (buffer-substring
1773                                                        (match-beginning 0)
1774                                                        (1- (match-end 0))))
1775                                               message-header-format-alist)
1776                                         message-header-format-alist)))
1777                (- max rank)
1778              (1+ max)))))
1779       (message-sort-headers-1))))
1780
1781 \f
1782
1783 ;;;
1784 ;;; Message mode
1785 ;;;
1786
1787 ;;; Set up keymap.
1788
1789 (defvar message-mode-map nil)
1790
1791 (unless message-mode-map
1792   (setq message-mode-map (make-keymap))
1793   (set-keymap-parent message-mode-map text-mode-map)
1794   (define-key message-mode-map "\C-c?" 'describe-mode)
1795
1796   (define-key message-mode-map "\C-c\C-f\C-t" 'message-goto-to)
1797   (define-key message-mode-map "\C-c\C-f\C-o" 'message-goto-from)
1798   (define-key message-mode-map "\C-c\C-f\C-b" 'message-goto-bcc)
1799   (define-key message-mode-map "\C-c\C-f\C-w" 'message-goto-fcc)
1800   (define-key message-mode-map "\C-c\C-f\C-c" 'message-goto-cc)
1801   (define-key message-mode-map "\C-c\C-f\C-s" 'message-goto-subject)
1802   ;; (define-key message-mode-map "\C-c\C-f\C-r" 'message-goto-reply-to)
1803   (define-key message-mode-map "\C-c\C-f\C-r" 'message-goto-mail-reply-to)
1804   (define-key message-mode-map "\C-c\C-f\C-m" 'message-goto-mail-followup-to)
1805   (define-key message-mode-map "\C-c\C-f\C-n" 'message-goto-newsgroups)
1806   (define-key message-mode-map "\C-c\C-f\C-d" 'message-goto-distribution)
1807   (define-key message-mode-map "\C-c\C-f\C-f" 'message-goto-followup-to)
1808   (define-key message-mode-map "\C-c\C-f\C-m" 'message-goto-mail-followup-to)
1809   (define-key message-mode-map "\C-c\C-f\C-k" 'message-goto-keywords)
1810   (define-key message-mode-map "\C-c\C-f\C-u" 'message-goto-summary)
1811   (define-key message-mode-map "\C-c\C-f\C-i" 'message-insert-or-toggle-importance)
1812   (define-key message-mode-map "\C-c\C-f\C-a" 'message-gen-unsubscribed-mft)
1813   (define-key message-mode-map "\C-c\C-b" 'message-goto-body)
1814   (define-key message-mode-map "\C-c\C-i" 'message-goto-signature)
1815   (define-key message-mode-map "\C-c\C-fc" 'message-goto-mail-copies-to)
1816
1817   (define-key message-mode-map "\C-c\C-t" 'message-insert-to)
1818   (define-key message-mode-map "\C-c\C-n" 'message-insert-newsgroups)
1819
1820   (define-key message-mode-map "\C-c\C-u" 'message-insert-or-toggle-importance)
1821   (define-key message-mode-map "\C-c\M-n" 'message-insert-disposition-notification-to)
1822
1823   (define-key message-mode-map "\C-c\C-y" 'message-yank-original)
1824   (define-key message-mode-map "\C-c\M-\C-y" 'message-yank-buffer)
1825   (define-key message-mode-map "\C-c\C-q" 'message-fill-yanked-message)
1826   (define-key message-mode-map "\C-c\C-w" 'message-insert-signature)
1827   (define-key message-mode-map "\C-c\M-h" 'message-insert-headers)
1828   (define-key message-mode-map "\C-c\C-r" 'message-caesar-buffer-body)
1829   (define-key message-mode-map "\C-c\C-o" 'message-sort-headers)
1830   (define-key message-mode-map "\C-c\M-r" 'message-rename-buffer)
1831
1832   (define-key message-mode-map "\C-c\C-c" 'message-send-and-exit)
1833   (define-key message-mode-map "\C-c\C-s" 'message-send)
1834   (define-key message-mode-map "\C-c\C-k" 'message-kill-buffer)
1835   (define-key message-mode-map "\C-c\C-d" 'message-dont-send)
1836   (define-key message-mode-map "\C-c\n" 'gnus-delay-article)
1837
1838   (define-key message-mode-map "\C-c\C-e" 'message-elide-region)
1839   (define-key message-mode-map "\C-c\C-v" 'message-delete-not-region)
1840   (define-key message-mode-map "\C-c\C-z" 'message-kill-to-signature)
1841   (define-key message-mode-map "\M-\r" 'message-newline-and-reformat)
1842   ;;(define-key message-mode-map "\M-q" 'message-fill-paragraph)
1843
1844   (define-key message-mode-map "\C-a" 'message-beginning-of-line)
1845   (define-key message-mode-map "\t" 'message-tab)
1846   (define-key message-mode-map "\M-;" 'comment-region)
1847
1848   (define-key message-mode-map "\C-x\C-s" 'message-save-drafts)
1849   (define-key message-mode-map "\C-xk" 'message-mimic-kill-buffer))
1850
1851 (easy-menu-define
1852  message-mode-menu message-mode-map "Message Menu."
1853  `("Message"
1854    ["Sort Headers" message-sort-headers t]
1855    ["Yank Original" message-yank-original t]
1856    ["Fill Yanked Message" message-fill-yanked-message t]
1857    ["Insert Signature" message-insert-signature t]
1858    ["Caesar (rot13) Message" message-caesar-buffer-body t]
1859    ["Caesar (rot13) Region" message-caesar-region (mark t)]
1860    ["Elide Region" message-elide-region (mark t)]
1861    ["Delete Outside Region" message-delete-not-region (mark t)]
1862    ["Kill To Signature" message-kill-to-signature t]
1863    ["Newline and Reformat" message-newline-and-reformat t]
1864    ["Rename buffer" message-rename-buffer t]
1865    ["Flag As Important" message-insert-importance-high
1866     ,@(if (featurep 'xemacs) '(t)
1867         '(:help "Mark this message as important"))]
1868    ["Flag As Unimportant" message-insert-importance-low
1869     ,@(if (featurep 'xemacs) '(t)
1870         '(:help "Mark this message as unimportant"))]
1871    ["Request Receipt"
1872     message-insert-disposition-notification-to
1873     ,@(if (featurep 'xemacs) '(t)
1874         '(:help "Request a Disposition Notification of this article"))]
1875    ["Spellcheck" ispell-message
1876     ,@(if (featurep 'xemacs) '(t)
1877         '(:help "Spellcheck this message"))]
1878    ["Attach file as MIME" mime-edit-insert-file
1879     ,@(if (featurep 'xemacs) '(t)
1880         '(:help "Attach a file at point"))]
1881    "----"
1882    ["Send Message" message-send-and-exit
1883     ,@(if (featurep 'xemacs) '(t)
1884         '(:help "Send this message"))]
1885    ["Postpone Message" message-dont-send
1886     ,@(if (featurep 'xemacs) '(t)
1887         '(:help "File this draft message and exit"))]
1888    ["Send at Specific Time" gnus-delay-article
1889     ,@(if (featurep 'xemacs) '(t)
1890         '(:help "Ask, then arrange to send message at that time"))]
1891    ["Kill Message" message-kill-buffer
1892     ,@(if (featurep 'xemacs) '(t)
1893         '(:help "Delete this message without sending"))]))
1894
1895 (easy-menu-define
1896  message-mode-field-menu message-mode-map ""
1897  '("Field"
1898    ["Fetch To" message-insert-to t]
1899    ["Fetch Newsgroups" message-insert-newsgroups t]
1900    "----"
1901    ["To" message-goto-to t]
1902    ["From" message-goto-from t]
1903    ["Subject" message-goto-subject t]
1904    ["Cc" message-goto-cc t]
1905    ["Reply-To" message-goto-reply-to t]
1906    ["Mail-Reply-To" message-goto-mail-reply-to t]
1907    ["Mail-Followup-To" message-goto-mail-followup-to t]
1908    ["Mail-Copies-To" message-goto-mail-copies-to t]
1909    ["Summary" message-goto-summary t]
1910    ["Keywords" message-goto-keywords t]
1911    ["Newsgroups" message-goto-newsgroups t]
1912    ["Followup-To" message-goto-followup-to t]
1913    ["Mail-Followup-To" message-goto-mail-followup-to t]
1914    ["Distribution" message-goto-distribution t]
1915    ["Body" message-goto-body t]
1916    ["Signature" message-goto-signature t]))
1917
1918 (defvar message-tool-bar-map nil)
1919
1920 (eval-when-compile
1921   (defvar facemenu-add-face-function)
1922   (defvar facemenu-remove-face-function))
1923
1924 ;;; Forbidden properties
1925 ;;
1926 ;; We use `after-change-functions' to keep special text properties
1927 ;; that interfer with the normal function of message mode out of the
1928 ;; buffer.
1929
1930 (defcustom message-strip-special-text-properties t
1931   "Strip special properties from the message buffer.
1932
1933 Emacs has a number of special text properties which can break message
1934 composing in various ways.  If this option is set, message will strip
1935 these properties from the message composition buffer.  However, some
1936 packages requires these properties to be present in order to work.
1937 If you use one of these packages, turn this option off, and hope the
1938 message composition doesn't break too bad."
1939   :group 'message-various
1940   :type 'boolean)
1941
1942 (defconst message-forbidden-properties
1943   ;; No reason this should be clutter up customize.  We make it a
1944   ;; property list (rather than a list of property symbols), to be
1945   ;; directly useful for `remove-text-properties'.
1946   '(field nil read-only nil intangible nil invisible nil
1947           mouse-face nil modification-hooks nil insert-in-front-hooks nil
1948           insert-behind-hooks nil point-entered nil point-left nil)
1949   ;; Other special properties:
1950   ;; category, face, display: probably doesn't do any harm.
1951   ;; fontified: is used by font-lock.
1952   ;; syntax-table, local-map: I dunno.
1953   ;; We need to add XEmacs names to the list.
1954   "Property list of with properties.forbidden in message buffers.
1955 The values of the properties are ignored, only the property names are used.")
1956
1957 (defun message-tamago-not-in-use-p (pos)
1958   "Return t when tamago version 4 is not in use at the cursor position.
1959 Tamago version 4 is a popular input method for writing Japanese text.
1960 It uses the properties `intangible', `invisible', `modification-hooks'
1961 and `read-only' when translating ascii or kana text to kanji text.
1962 These properties are essential to work, so we should never strip them."
1963   (not (and (boundp 'egg-modefull-mode)
1964             (symbol-value 'egg-modefull-mode)
1965             (or (memq (get-text-property pos 'intangible)
1966                       '(its-part-1 its-part-2))
1967                 (get-text-property pos 'egg-end)
1968                 (get-text-property pos 'egg-lang)
1969                 (get-text-property pos 'egg-start)))))
1970
1971 (defun message-strip-forbidden-properties (begin end &optional old-length)
1972   "Strip forbidden properties between BEGIN and END, ignoring the third arg.
1973 This function is intended to be called from `after-change-functions'.
1974 See also `message-forbidden-properties'."
1975   (when (and message-strip-special-text-properties
1976              (message-tamago-not-in-use-p begin)
1977              ;; Check whether the invisible MIME part is not inserted.
1978              (not (text-property-any begin end 'mime-edit-invisible t)))
1979     (remove-text-properties begin end message-forbidden-properties)))
1980
1981 ;;;###autoload
1982 (define-derived-mode message-mode text-mode "Message"
1983   "Major mode for editing mail and news to be sent.
1984 Like Text Mode but with these additional commands:\\<message-mode-map>
1985 C-c C-s  `message-send' (send the message)  C-c C-c  `message-send-and-exit'
1986 C-c C-d  Postpone sending the message       C-c C-k  Kill the message
1987 C-c C-f  move to a header field (and create it if there isn't):
1988          C-c C-f C-t  move to To        C-c C-f C-s  move to Subject
1989          C-c C-f C-c  move to Cc        C-c C-f C-b  move to Bcc
1990          C-c C-f C-w  move to Fcc       C-c C-f C-r  move to Reply-To
1991          C-c C-f C-u  move to Summary   C-c C-f C-n  move to Newsgroups
1992          C-c C-f C-k  move to Keywords  C-c C-f C-d  move to Distribution
1993          C-c C-f C-o  move to From (\"Originator\")
1994          C-c C-f C-f  move to Followup-To
1995          C-c C-f C-m  move to Mail-Followup-To
1996          C-c C-f C-i  cycle through Importance values
1997          C-c C-f c    move to Mail-Copies-To
1998 C-c C-t  `message-insert-to' (add a To header to a news followup)
1999 C-c C-n  `message-insert-newsgroups' (add a Newsgroup header to a news reply)
2000 C-c C-b  `message-goto-body' (move to beginning of message text).
2001 C-c C-i  `message-goto-signature' (move to the beginning of the signature).
2002 C-c C-w  `message-insert-signature' (insert `message-signature-file' file).
2003 C-c C-y  `message-yank-original' (insert current message, if any).
2004 C-c C-q  `message-fill-yanked-message' (fill what was yanked).
2005 C-c C-e  `message-elide-region' (elide the text between point and mark).
2006 C-c C-v  `message-delete-not-region' (remove the text outside the region).
2007 C-c C-z  `message-kill-to-signature' (kill the text up to the signature).
2008 C-c C-r  `message-caesar-buffer-body' (rot13 the message body).
2009 C-c C-u  `message-insert-or-toggle-importance'  (insert or cycle importance).
2010 C-c M-n  `message-insert-disposition-notification-to'  (request receipt).
2011 M-RET    `message-newline-and-reformat' (break the line and reformat)."
2012   (setq local-abbrev-table text-mode-abbrev-table)
2013   (set (make-local-variable 'message-reply-buffer) nil)
2014   (make-local-variable 'message-send-actions)
2015   (make-local-variable 'message-exit-actions)
2016   (make-local-variable 'message-kill-actions)
2017   (make-local-variable 'message-postpone-actions)
2018   (make-local-variable 'message-draft-article)
2019   (setq buffer-offer-save t)
2020   (set (make-local-variable 'facemenu-add-face-function)
2021        (lambda (face end)
2022          (let ((face-fun (cdr (assq face message-face-alist))))
2023            (if face-fun
2024                (funcall face-fun (point) end)
2025              (error "Face %s not configured for %s mode" face mode-name)))
2026          ""))
2027   (set (make-local-variable 'facemenu-remove-face-function) t)
2028   (set (make-local-variable 'message-reply-headers) nil)
2029   (make-local-variable 'message-user-agent)
2030   (make-local-variable 'message-post-method)
2031   (set (make-local-variable 'message-sent-message-via) nil)
2032   (set (make-local-variable 'message-checksum) nil)
2033   (make-local-variable 'message-parameter-alist)
2034   (setq message-parameter-alist
2035         (copy-sequence message-startup-parameter-alist))
2036   (message-setup-fill-variables)
2037   ;; Allow using comment commands to add/remove quoting.
2038   (set (make-local-variable 'comment-start) message-yank-prefix)
2039   (if (featurep 'xemacs)
2040       (message-setup-toolbar)
2041     (set (make-local-variable 'font-lock-defaults)
2042          '(message-font-lock-keywords t))
2043     (if (boundp 'tool-bar-map)
2044         (set (make-local-variable 'tool-bar-map) (message-tool-bar-map))))
2045   (easy-menu-add message-mode-menu message-mode-map)
2046   (easy-menu-add message-mode-field-menu message-mode-map)
2047   ;; make-local-hook is harmless though obsolete in Emacs 21.
2048   ;; Emacs 20 and XEmacs need make-local-hook.
2049   (make-local-hook 'after-change-functions)
2050   ;; Mmmm... Forbidden properties...
2051   (add-hook 'after-change-functions 'message-strip-forbidden-properties
2052             nil 'local)
2053   ;; Allow mail alias things.
2054   (when (eq message-mail-alias-type 'abbrev)
2055     (if (fboundp 'mail-abbrevs-setup)
2056         (mail-abbrevs-setup)
2057       (mail-aliases-setup)))
2058   (unless buffer-file-name
2059     (message-set-auto-save-file-name))
2060   (set (make-local-variable 'indent-tabs-mode) nil)) ;No tabs for indentation.
2061
2062 (defun message-setup-fill-variables ()
2063   "Setup message fill variables."
2064   (set (make-local-variable 'fill-paragraph-function)
2065        'message-fill-paragraph)
2066   (make-local-variable 'paragraph-separate)
2067   (make-local-variable 'paragraph-start)
2068   (make-local-variable 'adaptive-fill-regexp)
2069   (unless (boundp 'adaptive-fill-first-line-regexp)
2070     (setq adaptive-fill-first-line-regexp nil))
2071   (make-local-variable 'adaptive-fill-first-line-regexp)
2072   (let ((quote-prefix-regexp
2073          ;; User should change message-cite-prefix-regexp if
2074          ;; message-yank-prefix is set to an abnormal value.
2075          (concat "\\(" message-cite-prefix-regexp "\\)[ \t]*")))
2076     (setq paragraph-start
2077           (concat
2078            (regexp-quote mail-header-separator) "$\\|"
2079            "[ \t]*$\\|"                 ; blank lines
2080            "-- $\\|"                    ; signature delimiter
2081            "---+$\\|"                   ; delimiters for forwarded messages
2082            page-delimiter "$\\|"        ; spoiler warnings
2083            ".*wrote:$\\|"               ; attribution lines
2084            quote-prefix-regexp "$"))    ; empty lines in quoted text
2085     (setq paragraph-separate paragraph-start)
2086     (setq adaptive-fill-regexp
2087           (concat quote-prefix-regexp "\\|" adaptive-fill-regexp))
2088     (setq adaptive-fill-first-line-regexp
2089           (concat quote-prefix-regexp "\\|"
2090                   adaptive-fill-first-line-regexp)))
2091   (make-local-variable 'auto-fill-inhibit-regexp)
2092   ;;(setq auto-fill-inhibit-regexp "^[A-Z][^: \n\t]+:")
2093   (setq auto-fill-inhibit-regexp nil)
2094   (make-local-variable 'normal-auto-fill-function)
2095   (setq normal-auto-fill-function 'message-do-auto-fill)
2096   ;; KLUDGE: auto fill might already be turned on in `text-mode-hook'.
2097   ;; In that case, ensure that it uses the right function.  The real
2098   ;; solution would be not to use `define-derived-mode', and run
2099   ;; `text-mode-hook' ourself at the end of the mode.
2100   ;; -- Per Abrahamsen <abraham@dina.kvl.dk> Date: 2001-10-19.
2101   (when auto-fill-function
2102     (setq auto-fill-function normal-auto-fill-function)))
2103
2104 \f
2105
2106 ;;;
2107 ;;; Message mode commands
2108 ;;;
2109
2110 ;;; Movement commands
2111
2112 (defun message-goto-to ()
2113   "Move point to the To header."
2114   (interactive)
2115   (message-position-on-field "To"))
2116
2117 (defun message-goto-from ()
2118   "Move point to the From header."
2119   (interactive)
2120   (message-position-on-field "From"))
2121
2122 (defun message-goto-subject ()
2123   "Move point to the Subject header."
2124   (interactive)
2125   (message-position-on-field "Subject"))
2126
2127 (defun message-goto-cc ()
2128   "Move point to the Cc header."
2129   (interactive)
2130   (message-position-on-field "Cc" "To"))
2131
2132 (defun message-goto-bcc ()
2133   "Move point to the Bcc  header."
2134   (interactive)
2135   (message-position-on-field "Bcc" "Cc" "To"))
2136
2137 (defun message-goto-fcc ()
2138   "Move point to the Fcc header."
2139   (interactive)
2140   (message-position-on-field "Fcc" "To" "Newsgroups"))
2141
2142 (defun message-goto-reply-to ()
2143   "Move point to the Reply-To header."
2144   (interactive)
2145   (message-position-on-field "Reply-To" "Subject"))
2146
2147 (defun message-goto-mail-reply-to ()
2148   "Move point to the Mail-Reply-To header."
2149   (interactive)
2150   (message-position-on-field "Mail-Reply-To" "Subject"))
2151
2152 (defun message-goto-mail-copies-to ()
2153   "Move point to the Mail-Copies-To header.  If the header is newly created,
2154 a string \"never\" is inserted in default."
2155   (interactive)
2156   (unless (message-position-on-field "Mail-Copies-To" "Subject")
2157     (insert "never")
2158     (backward-char 5)))
2159
2160 (defun message-goto-newsgroups ()
2161   "Move point to the Newsgroups header."
2162   (interactive)
2163   (message-position-on-field "Newsgroups"))
2164
2165 (defun message-goto-distribution ()
2166   "Move point to the Distribution header."
2167   (interactive)
2168   (message-position-on-field "Distribution"))
2169
2170 (defun message-goto-followup-to ()
2171   "Move point to the Followup-To header."
2172   (interactive)
2173   (message-position-on-field "Followup-To" "Newsgroups"))
2174
2175 (defun message-goto-mail-followup-to ()
2176   "Move point to the Mail-Followup-To header.  If the header is newly created
2177 and To field contains only one address, the address is inserted in default."
2178   (interactive)
2179   (unless (message-position-on-field "Mail-Followup-To" "Subject")
2180     (let ((start (point))
2181           addresses)
2182       (save-restriction
2183         (message-narrow-to-headers)
2184         (setq addresses (split-string (mail-strip-quoted-names
2185                                        (or (std11-fetch-field "to") ""))
2186                                       "[ \f\t\n\r\v,]+"))
2187         (when (eq 1 (length addresses))
2188           (goto-char start)
2189           (insert (car addresses))
2190           (goto-char start))))))
2191
2192 (defun message-goto-keywords ()
2193   "Move point to the Keywords header."
2194   (interactive)
2195   (message-position-on-field "Keywords" "Subject"))
2196
2197 (defun message-goto-summary ()
2198   "Move point to the Summary header."
2199   (interactive)
2200   (message-position-on-field "Summary" "Subject"))
2201
2202 (defun message-goto-body (&optional interactivep)
2203   "Move point to the beginning of the message body."
2204   (interactive (list t))
2205   (when (and interactivep
2206              (looking-at "[ \t]*\n"))
2207     (expand-abbrev))
2208   (goto-char (point-min))
2209   (or (search-forward (concat "\n" mail-header-separator "\n") nil t)
2210       (search-forward-regexp "[^:]+:\\([^\n]\\|\n[ \t]\\)+\n\n" nil t)))
2211
2212 (defun message-goto-eoh ()
2213   "Move point to the end of the headers."
2214   (interactive)
2215   (message-goto-body)
2216   (forward-line -1))
2217
2218 (defun message-goto-signature ()
2219   "Move point to the beginning of the message signature.
2220 If there is no signature in the article, go to the end and
2221 return nil."
2222   (interactive)
2223   (goto-char (point-min))
2224   (if (re-search-forward message-signature-separator nil t)
2225       (forward-line 1)
2226     (goto-char (point-max))
2227     nil))
2228
2229 (defun message-gen-unsubscribed-mft (&optional include-cc)
2230   "Insert a reasonable MFT header in a post to an unsubscribed list.
2231 When making original posts to a mailing list you are not subscribed to,
2232 you have to type in a MFT header by hand.  The contents, usually, are
2233 the addresses of the list and your own address.  This function inserts
2234 such a header automatically.  It fetches the contents of the To: header
2235 in the current mail buffer, and appends the current user-mail-address.
2236
2237 If the optional argument `include-cc' is non-nil, the addresses in the
2238 Cc: header are also put into the MFT."
2239
2240   (interactive)
2241   (message-remove-header "Mail-Followup-To")
2242   (let* ((cc (and include-cc (message-fetch-field "Cc")))
2243          (tos (if cc
2244                   (concat (message-fetch-field "To") "," cc)
2245                 (message-fetch-field "To"))))
2246     (message-goto-mail-followup-to)
2247     (insert (concat tos ", " user-mail-address))))
2248
2249 \f
2250
2251 (defun message-insert-to (&optional force)
2252   "Insert a To header that points to the author of the article being replied to.
2253 If the original author requested not to be sent mail, the function signals
2254 an error.
2255 With the prefix argument FORCE, insert the header anyway."
2256   (interactive "P")
2257   (let ((co (message-fetch-reply-field "mail-copies-to")))
2258     (when (and (null force)
2259                co
2260                (or (equal (downcase co) "never")
2261                    (equal (downcase co) "nobody")))
2262       (error "The user has requested not to have copies sent via mail")))
2263   (when (and (message-position-on-field "To")
2264              (mail-fetch-field "to")
2265              (not (string-match "\\` *\\'" (mail-fetch-field "to"))))
2266     (insert ", "))
2267   (insert (or (message-fetch-reply-field "mail-reply-to")
2268               (message-fetch-reply-field "reply-to")
2269               (message-fetch-reply-field "from") "")))
2270
2271 (defun message-widen-reply ()
2272   "Widen the reply to include maximum recipients."
2273   (interactive)
2274   (let ((follow-to
2275          (and message-reply-buffer
2276               (buffer-name message-reply-buffer)
2277               (save-excursion
2278                 (set-buffer message-reply-buffer)
2279                 (message-get-reply-headers t)))))
2280     (save-excursion
2281       (save-restriction
2282         (message-narrow-to-headers)
2283         (dolist (elem follow-to)
2284           (message-remove-header (symbol-name (car elem)))
2285           (goto-char (point-min))
2286           (insert (symbol-name (car elem)) ": "
2287                   (cdr elem) "\n"))))))
2288
2289 (defun message-insert-newsgroups ()
2290   "Insert the Newsgroups header from the article being replied to."
2291   (interactive)
2292   (when (and (message-position-on-field "Newsgroups")
2293              (mail-fetch-field "newsgroups")
2294              (not (string-match "\\` *\\'" (mail-fetch-field "newsgroups"))))
2295     (insert ","))
2296   (insert (or (message-fetch-reply-field "newsgroups") "")))
2297
2298 \f
2299
2300 ;;; Various commands
2301
2302 (defun message-delete-not-region (beg end)
2303   "Delete everything in the body of the current message outside of the region."
2304   (interactive "r")
2305   (let (citeprefix)
2306     (save-excursion
2307       (goto-char beg)
2308       ;; snarf citation prefix, if appropriate
2309       (unless (eq (point) (progn (beginning-of-line) (point)))
2310         (when (looking-at message-cite-prefix-regexp)
2311           (setq citeprefix (match-string 0))))
2312       (goto-char end)
2313       (delete-region (point) (if (not (message-goto-signature))
2314                                  (point)
2315                                (forward-line -2)
2316                                (point)))
2317       (insert "\n")
2318       (goto-char beg)
2319       (delete-region beg (progn (message-goto-body)
2320                                 (forward-line 2)
2321                                 (point)))
2322       (when citeprefix
2323         (insert citeprefix))))
2324   (when (message-goto-signature)
2325     (forward-line -2)))
2326
2327 (defun message-kill-to-signature ()
2328   "Deletes all text up to the signature."
2329   (interactive)
2330   (let ((point (point)))
2331     (message-goto-signature)
2332     (unless (eobp)
2333       (forward-line -2))
2334     (kill-region point (point))
2335     (unless (bolp)
2336       (insert "\n"))))
2337
2338 (defun message-newline-and-reformat (&optional arg not-break)
2339   "Insert four newlines, and then reformat if inside quoted text.
2340 Prefix arg means justify as well."
2341   (interactive (list (if current-prefix-arg 'full)))
2342   (let (quoted point beg end leading-space bolp)
2343     (setq point (point))
2344     (beginning-of-line)
2345     (setq beg (point))
2346     (setq bolp (= beg point))
2347     ;; Find first line of the paragraph.
2348     (if not-break
2349         (while (and (not (eobp))
2350                     (not (looking-at message-cite-prefix-regexp))
2351                     (looking-at paragraph-start))
2352           (forward-line 1)))
2353     ;; Find the prefix
2354     (when (looking-at message-cite-prefix-regexp)
2355       (setq quoted (match-string 0))
2356       (goto-char (match-end 0))
2357       (looking-at "[ \t]*")
2358       (setq leading-space (match-string 0)))
2359     (if (and quoted
2360              (not not-break)
2361              (not bolp)
2362              (< (- point beg) (length quoted)))
2363         ;; break inside the cite prefix.
2364         (setq quoted nil
2365               end nil))
2366     (if quoted
2367         (progn
2368           (forward-line 1)
2369           (while (and (not (eobp))
2370                       (not (looking-at paragraph-separate))
2371                       (looking-at message-cite-prefix-regexp)
2372                       (equal quoted (match-string 0)))
2373             (goto-char (match-end 0))
2374             (looking-at "[ \t]*")
2375             (if (> (length leading-space) (length (match-string 0)))
2376                 (setq leading-space (match-string 0)))
2377             (forward-line 1))
2378           (setq end (point))
2379           (goto-char beg)
2380           (while (and (if (bobp) nil (forward-line -1) t)
2381                       (not (looking-at paragraph-start))
2382                       (looking-at message-cite-prefix-regexp)
2383                       (equal quoted (match-string 0)))
2384             (setq beg (point))
2385             (goto-char (match-end 0))
2386             (looking-at "[ \t]*")
2387             (if (> (length leading-space) (length (match-string 0)))
2388                 (setq leading-space (match-string 0)))))
2389       (while (and (not (eobp))
2390                   (not (looking-at paragraph-separate))
2391                   (not (looking-at message-cite-prefix-regexp)))
2392         (forward-line 1))
2393       (setq end (point))
2394       (goto-char beg)
2395       (while (and (if (bobp) nil (forward-line -1) t)
2396                   (not (looking-at paragraph-start))
2397                   (not (looking-at message-cite-prefix-regexp)))
2398         (setq beg (point))))
2399     (goto-char point)
2400     (save-restriction
2401       (narrow-to-region beg end)
2402       (if not-break
2403           (setq point nil)
2404         (if bolp
2405             (newline)
2406           (newline)
2407           (newline))
2408         (setq point (point))
2409         ;; (newline 2) doesn't mark both newline's as hard, so call
2410         ;; newline twice. -jas
2411         (newline)
2412         (newline)
2413         (delete-region (point) (re-search-forward "[ \t]*"))
2414         (when (and quoted (not bolp))
2415           (insert quoted leading-space)))
2416       (if quoted
2417           (let* ((adaptive-fill-regexp
2418                   (regexp-quote (concat quoted leading-space)))
2419                  (adaptive-fill-first-line-regexp
2420                   adaptive-fill-regexp ))
2421             (fill-paragraph arg))
2422         (fill-paragraph arg))
2423       (if point (goto-char point)))))
2424
2425 (defun message-fill-paragraph (&optional arg)
2426   "Like `fill-paragraph'."
2427   (interactive (list (if current-prefix-arg 'full)))
2428   (if (and (boundp 'filladapt-mode) filladapt-mode)
2429       nil
2430     (message-newline-and-reformat arg t)
2431     t))
2432
2433 ;; Is it better to use `mail-header-end'?
2434 (defun message-point-in-header-p ()
2435   "Return t if point is in the header."
2436   (save-excursion
2437     (let ((p (point)))
2438       (goto-char (point-min))
2439       (not (re-search-forward
2440             (concat "^" (regexp-quote mail-header-separator) "\n")
2441             p t)))))
2442
2443 (defun message-do-auto-fill ()
2444   "Like `do-auto-fill', but don't fill in message header."
2445   (unless (message-point-in-header-p)
2446     (do-auto-fill)))
2447
2448 (defun message-insert-signature (&optional force)
2449   "Insert a signature.  See documentation for variable `message-signature'."
2450   (interactive (list 0))
2451   (let* ((signature
2452           (cond
2453            ((and (null message-signature)
2454                  (eq force 0))
2455             (save-excursion
2456               (goto-char (point-max))
2457               (not (re-search-backward message-signature-separator nil t))))
2458            ((and (null message-signature)
2459                  force)
2460             t)
2461            ((message-functionp message-signature)
2462             (funcall message-signature))
2463            ((listp message-signature)
2464             (eval message-signature))
2465            (t message-signature)))
2466          (signature
2467           (cond ((stringp signature)
2468                  signature)
2469                 ((and (eq t signature)
2470                       message-signature-file
2471                       (file-exists-p message-signature-file))
2472                  signature))))
2473     (when signature
2474       (goto-char (point-max))
2475       ;; Insert the signature.
2476       (unless (bolp)
2477         (insert "\n"))
2478       (insert "\n" message-signature-separator-for-insertion)
2479       (unless (bolp)
2480         (insert "\n"))
2481       (if (eq signature t)
2482           (insert-file-contents message-signature-file)
2483         (insert signature))
2484       (goto-char (point-max))
2485       (or (bolp) (insert "\n")))))
2486
2487 (defun message-insert-importance-high ()
2488   "Insert header to mark message as important."
2489   (interactive)
2490   (save-excursion
2491     (message-remove-header "Importance")
2492     (message-goto-eoh)
2493     (insert "Importance: high\n")))
2494
2495 (defun message-insert-importance-low ()
2496   "Insert header to mark message as unimportant."
2497   (interactive)
2498   (save-excursion
2499     (message-remove-header "Importance")
2500     (message-goto-eoh)
2501     (insert "Importance: low\n")))
2502
2503 (defun message-insert-or-toggle-importance ()
2504   "Insert a \"Importance: high\" header, or cycle through the header values.
2505 The three allowed values according to RFC 1327 are `high', `normal'
2506 and `low'."
2507   (interactive)
2508   (save-excursion
2509     (let ((valid '("high" "normal" "low"))
2510           (new "high")
2511           cur)
2512       (when (setq cur (message-fetch-field "Importance"))
2513         (message-remove-header "Importance")
2514         (setq new (cond ((string= cur "high")
2515                          "low")
2516                         ((string= cur "low")
2517                          "normal")
2518                         (t
2519                          "high"))))
2520       (message-goto-eoh)
2521       (insert (format "Importance: %s\n" new)))))
2522
2523 (defun message-insert-disposition-notification-to ()
2524   "Request a disposition notification (return receipt) to this message.
2525 Note that this should not be used in newsgroups."
2526   (interactive)
2527   (save-excursion
2528     (message-remove-header "Disposition-Notification-To")
2529     (message-goto-eoh)
2530     (insert (format "Disposition-Notification-To: %s\n"
2531                     (or (message-fetch-field "From") (message-make-from))))))
2532
2533 (defun message-elide-region (b e)
2534   "Elide the text in the region.
2535 An ellipsis (from `message-elide-ellipsis') will be inserted where the
2536 text was killed."
2537   (interactive "r")
2538   (kill-region b e)
2539   (insert message-elide-ellipsis))
2540
2541 (defvar message-caesar-translation-table nil)
2542
2543 (defun message-caesar-region (b e &optional n)
2544   "Caesar rotate region B to E by N, default 13, for decrypting netnews."
2545   (interactive
2546    (list
2547     (min (point) (or (mark t) (point)))
2548     (max (point) (or (mark t) (point)))
2549     (when current-prefix-arg
2550       (prefix-numeric-value current-prefix-arg))))
2551
2552   (setq n (if (numberp n) (mod n 26) 13)) ;canonize N
2553   (unless (or (zerop n)                 ; no action needed for a rot of 0
2554               (= b e))                  ; no region to rotate
2555     ;; We build the table, if necessary.
2556     (when (or (not message-caesar-translation-table)
2557               (/= (aref message-caesar-translation-table ?a) (+ ?a n)))
2558       (setq message-caesar-translation-table
2559             (message-make-caesar-translation-table n)))
2560     (translate-region b e message-caesar-translation-table)))
2561
2562 (defun message-make-caesar-translation-table (n)
2563   "Create a rot table with offset N."
2564   (let ((i -1)
2565         (table (make-string 256 0)))
2566     (while (< (incf i) 256)
2567       (aset table i i))
2568     (concat
2569      (substring table 0 ?A)
2570      (substring table (+ ?A n) (+ ?A n (- 26 n)))
2571      (substring table ?A (+ ?A n))
2572      (substring table (+ ?A 26) ?a)
2573      (substring table (+ ?a n) (+ ?a n (- 26 n)))
2574      (substring table ?a (+ ?a n))
2575      (substring table (+ ?a 26) 255))))
2576
2577 (defun message-caesar-buffer-body (&optional rotnum)
2578   "Caesar rotate all letters in the current buffer by 13 places.
2579 Used to encode/decode possibly offensive messages (commonly in rec.humor).
2580 With prefix arg, specifies the number of places to rotate each letter forward.
2581 Mail and USENET news headers are not rotated."
2582   (interactive (if current-prefix-arg
2583                    (list (prefix-numeric-value current-prefix-arg))
2584                  (list nil)))
2585   (save-excursion
2586     (save-restriction
2587       (when (message-goto-body)
2588         (narrow-to-region (point) (point-max)))
2589       (message-caesar-region (point-min) (point-max) rotnum))))
2590
2591 (defun message-pipe-buffer-body (program)
2592   "Pipe the message body in the current buffer through PROGRAM."
2593   (save-excursion
2594     (save-restriction
2595       (when (message-goto-body)
2596         (narrow-to-region (point) (point-max)))
2597       (shell-command-on-region
2598        (point-min) (point-max) program nil t))))
2599
2600 (defun message-rename-buffer (&optional enter-string)
2601   "Rename the *message* buffer to \"*message* RECIPIENT\".
2602 If the function is run with a prefix, it will ask for a new buffer
2603 name, rather than giving an automatic name."
2604   (interactive "Pbuffer name: ")
2605   (save-excursion
2606     (save-restriction
2607       (goto-char (point-min))
2608       (narrow-to-region (point)
2609                         (search-forward mail-header-separator nil 'end))
2610       (let* ((mail-to (or
2611                        (if (message-news-p) (message-fetch-field "Newsgroups")
2612                          (message-fetch-field "To"))
2613                        ""))
2614              (mail-trimmed-to
2615               (if (string-match "," mail-to)
2616                   (concat (substring mail-to 0 (match-beginning 0)) ", ...")
2617                 mail-to))
2618              (name-default (concat "*message* " mail-trimmed-to))
2619              (name (if enter-string
2620                        (read-string "New buffer name: " name-default)
2621                      name-default)))
2622         (rename-buffer name t)))))
2623
2624 (defun message-fill-yanked-message (&optional justifyp)
2625   "Fill the paragraphs of a message yanked into this one.
2626 Numeric argument means justify as well."
2627   (interactive "P")
2628   (save-excursion
2629     (goto-char (point-min))
2630     (search-forward (concat "\n" mail-header-separator "\n") nil t)
2631     (let ((fill-prefix message-yank-prefix))
2632       (fill-individual-paragraphs (point) (point-max) justifyp))))
2633
2634 (defun message-indent-citation ()
2635   "Modify text just inserted from a message to be cited.
2636 The inserted text should be the region.
2637 When this function returns, the region is again around the modified text.
2638
2639 Normally, indent each nonblank line `message-indentation-spaces' spaces.
2640 However, if `message-yank-prefix' is non-nil, insert that prefix on each line."
2641   (let ((start (point)))
2642     ;; Remove unwanted headers.
2643     (when message-ignored-cited-headers
2644       (let (all-removed)
2645         (save-restriction
2646           (narrow-to-region
2647            (goto-char start)
2648            (if (search-forward "\n\n" nil t)
2649                (1- (point))
2650              (point)))
2651           (message-remove-header message-ignored-cited-headers t)
2652           (when (= (point-min) (point-max))
2653             (setq all-removed t))
2654           (goto-char (point-max)))
2655         (if all-removed
2656             (goto-char start)
2657           (forward-line 1))))
2658     ;; Delete blank lines at the start of the buffer.
2659     (while (and (point-min)
2660                 (eolp)
2661                 (not (eobp)))
2662       (message-delete-line))
2663     ;; Delete blank lines at the end of the buffer.
2664     (goto-char (point-max))
2665     (unless (bolp)
2666       (insert "\n"))
2667     (while (and (zerop (forward-line -1))
2668                 (looking-at "$"))
2669       (message-delete-line))
2670     ;; Do the indentation.
2671     (if (null message-yank-prefix)
2672         (indent-rigidly start (mark t) message-indentation-spaces)
2673       (save-excursion
2674         (goto-char start)
2675         (while (< (point) (mark t))
2676           (if (or (looking-at ">") (looking-at "^$"))
2677               (insert message-yank-cited-prefix)
2678             (insert message-yank-prefix))
2679           (forward-line 1))))
2680     (goto-char start)))
2681
2682 (defun message-list-references (refs-list &rest refs-strs)
2683   "Add `Message-ID's which appear in REFS-STRS but not in REFS-LIST,
2684 to REFS-LIST."
2685   (let (refs ref id saved-id)
2686     (when (and refs-list
2687                (integerp message-list-references-add-position))
2688       (let ((pos message-list-references-add-position))
2689         (while (and refs-list
2690                     (> pos 0))
2691           (push (pop refs-list) saved-id)
2692           (setq pos (1- pos)))))
2693     (while refs-strs
2694       (when (setq refs (pop refs-strs))
2695         (setq refs (std11-parse-msg-ids (std11-lexical-analyze refs)))
2696         (while refs
2697           (when (eq (car (setq ref (pop refs))) 'msg-id)
2698             (setq id (concat "<" (mapconcat 'cdr (cdr ref) "") ">"))
2699             (or (member id refs-list)
2700                 (member id saved-id)
2701                 (push id refs-list))))))
2702     (while saved-id
2703       (push (pop saved-id) refs-list))
2704     refs-list))
2705
2706 (defvar gnus-article-copy)
2707 (defun message-yank-original (&optional arg)
2708   "Insert the message being replied to, if any.
2709 Puts point before the text and mark after.
2710 Normally indents each nonblank line ARG spaces (default 3).  However,
2711 if `message-yank-prefix' is non-nil, insert that prefix on each line.
2712
2713 This function uses `message-cite-function' to do the actual citing.
2714
2715 Just \\[universal-argument] as argument means don't indent, insert no
2716 prefix, and don't delete any headers.
2717
2718 In addition, if `message-yank-add-new-references' is non-nil and this
2719 command is called interactively, new IDs from the yanked article will
2720 be added to \"References\" field.
2721 \(See also `message-yank-add-new-references'.)"
2722   (interactive "P")
2723   (let ((modified (buffer-modified-p))
2724         (buffer (message-eval-parameter message-reply-buffer))
2725         start end refs)
2726     (when (and buffer
2727                message-cite-function)
2728       (delete-windows-on buffer t)
2729       (insert-buffer buffer) ; mark will be set at the end of article.
2730       (setq start (point)
2731             end (mark t))
2732
2733       ;; Add new IDs to References field.
2734       (when (and message-yank-add-new-references (interactive-p))
2735         (save-excursion
2736           (save-restriction
2737             (message-narrow-to-headers)
2738             (setq refs (message-list-references
2739                         nil
2740                         (message-fetch-field "References")))
2741             (widen)
2742             (narrow-to-region start end)
2743             (std11-narrow-to-header)
2744             (when (setq refs (message-list-references
2745                               refs
2746                               (unless (eq message-yank-add-new-references
2747                                           'message-id-only)
2748                                 (or (message-fetch-field "References")
2749                                     (message-fetch-field "In-Reply-To")))
2750                               (message-fetch-field "Message-ID")))
2751               (widen)
2752               (message-narrow-to-headers)
2753               (goto-char (point-min))
2754               (let ((case-fold-search t))
2755                 (if (re-search-forward "^References:\\([\t ]+.+\n\\)+" nil t)
2756                     (replace-match "")
2757                   (goto-char (point-max))))
2758               (mail-header-format
2759                (list (or (assq 'References message-header-format-alist)
2760                          '(References . message-fill-references)))
2761                (list (cons 'References
2762                            (mapconcat 'identity (nreverse refs) " "))))
2763               (backward-delete-char 1)))))
2764
2765       (unless arg
2766         (if (and message-suspend-font-lock-when-citing
2767                  (boundp 'font-lock-mode)
2768                  (symbol-value 'font-lock-mode))
2769             (unwind-protect
2770                 (progn
2771                   (sit-for 0)
2772                   (font-lock-mode 0)
2773                   (funcall message-cite-function))
2774               (font-lock-mode 1))
2775           (funcall message-cite-function)))
2776       (message-exchange-point-and-mark)
2777       (unless (bolp)
2778         (insert ?\n))
2779       (unless modified
2780         (setq message-checksum (message-checksum))))))
2781
2782 (defun message-yank-buffer (buffer)
2783   "Insert BUFFER into the current buffer and quote it."
2784   (interactive "bYank buffer: ")
2785   (let ((message-reply-buffer buffer))
2786     (save-window-excursion
2787       (message-yank-original))))
2788
2789 (defun message-buffers ()
2790   "Return a list of active message buffers."
2791   (let (buffers)
2792     (save-excursion
2793       (dolist (buffer (buffer-list t))
2794         (set-buffer buffer)
2795         (when (and (eq major-mode 'message-mode)
2796                    (null message-sent-message-via))
2797           (push (buffer-name buffer) buffers))))
2798     (nreverse buffers)))
2799
2800 (defun message-cite-original-without-signature ()
2801   "Cite function in the standard Message manner."
2802   (let ((start (point))
2803         (end (mark t))
2804         (functions
2805          (when message-indent-citation-function
2806            (if (listp message-indent-citation-function)
2807                message-indent-citation-function
2808              (list message-indent-citation-function))))
2809         (message-reply-headers (or message-reply-headers
2810                                    (make-mail-header))))
2811     (mail-header-set-from message-reply-headers
2812                           (save-restriction
2813                             (narrow-to-region
2814                              (point)
2815                              (if (search-forward "\n\n" nil t)
2816                                  (1- (point))
2817                                (point-max)))
2818                             (or (message-fetch-field "from")
2819                                 "unknown sender")))
2820     ;; Allow undoing.
2821     (undo-boundary)
2822     (goto-char end)
2823     (when (re-search-backward message-signature-separator start t)
2824       ;; Also peel off any blank lines before the signature.
2825       (forward-line -1)
2826       (while (looking-at "^[ \t]*$")
2827         (forward-line -1))
2828       (forward-line 1)
2829       (delete-region (point) end)
2830       (unless (search-backward "\n\n" start t)
2831         ;; Insert a blank line if it is peeled off.
2832         (insert "\n")))
2833     (goto-char start)
2834     (while functions
2835       (funcall (pop functions)))
2836     (when message-citation-line-function
2837       (unless (bolp)
2838         (insert "\n"))
2839       (funcall message-citation-line-function))))
2840
2841 (eval-when-compile (defvar mail-citation-hook))         ;Compiler directive
2842 (defun message-cite-original ()
2843   "Cite function in the standard Message manner."
2844   (if (and (boundp 'mail-citation-hook)
2845            mail-citation-hook)
2846       (run-hooks 'mail-citation-hook)
2847     (let ((start (point))
2848           (end (mark t))
2849           (functions
2850            (when message-indent-citation-function
2851              (if (listp message-indent-citation-function)
2852                  message-indent-citation-function
2853                (list message-indent-citation-function))))
2854           (message-reply-headers (or message-reply-headers
2855                                      (make-mail-header))))
2856       (mail-header-set-from message-reply-headers
2857                             (save-restriction
2858                               (narrow-to-region
2859                                (point)
2860                                (if (search-forward "\n\n" nil t)
2861                                    (1- (point))
2862                                  (point-max)))
2863                               (or (message-fetch-field "from")
2864                                   "unknown sender")))
2865       (goto-char start)
2866       (while functions
2867         (funcall (pop functions)))
2868       (when message-citation-line-function
2869         (unless (bolp)
2870           (insert "\n"))
2871         (funcall message-citation-line-function)))))
2872
2873 (defun message-insert-citation-line ()
2874   "Insert a simple citation line."
2875   (when message-reply-headers
2876     (insert (mail-header-from message-reply-headers) " writes:\n\n")))
2877
2878 (defun message-position-on-field (header &rest afters)
2879   (let ((case-fold-search t))
2880     (save-restriction
2881       (narrow-to-region
2882        (goto-char (point-min))
2883        (progn
2884          (re-search-forward
2885           (concat "^" (regexp-quote mail-header-separator) "$"))
2886          (match-beginning 0)))
2887       (goto-char (point-min))
2888       (if (re-search-forward (concat "^" (regexp-quote header) ":") nil t)
2889           (progn
2890             (re-search-forward "^[^ \t]" nil 'move)
2891             (beginning-of-line)
2892             (skip-chars-backward "\n")
2893             t)
2894         (while (and afters
2895                     (not (re-search-forward
2896                           (concat "^" (regexp-quote (car afters)) ":")
2897                           nil t)))
2898           (pop afters))
2899         (when afters
2900           (re-search-forward "^[^ \t]" nil 'move)
2901           (beginning-of-line))
2902         (insert header ": \n")
2903         (forward-char -1)
2904         nil))))
2905
2906 (defun message-remove-signature ()
2907   "Remove the signature from the text between point and mark.
2908 The text will also be indented the normal way."
2909   (save-excursion
2910     (let ((start (point))
2911           mark)
2912       (if (not (re-search-forward message-signature-separator (mark t) t))
2913           ;; No signature here, so we just indent the cited text.
2914           (message-indent-citation)
2915         ;; Find the last non-empty line.
2916         (forward-line -1)
2917         (while (looking-at "[ \t]*$")
2918           (forward-line -1))
2919         (forward-line 1)
2920         (setq mark (set-marker (make-marker) (point)))
2921         (goto-char start)
2922         (message-indent-citation)
2923         ;; Enable undoing the deletion.
2924         (undo-boundary)
2925         (delete-region mark (mark t))
2926         (set-marker mark nil)))))
2927
2928 \f
2929
2930 ;;;
2931 ;;; Sending messages
2932 ;;;
2933
2934 ;; Avoid byte-compile warning.
2935 (defvar message-encoding-buffer nil)
2936 (defvar message-edit-buffer nil)
2937 (defvar message-mime-mode nil)
2938
2939 (defun message-send-and-exit (&optional arg)
2940   "Send message like `message-send', then, if no errors, exit from mail buffer."
2941   (interactive "P")
2942   (let ((buf (current-buffer))
2943         (actions message-exit-actions)
2944         (frame (selected-frame))
2945         (org-frame message-original-frame))
2946     (when (and (message-send arg)
2947                (buffer-name buf))
2948       (if message-kill-buffer-on-exit
2949           (kill-buffer buf)
2950         (bury-buffer buf)
2951         (when (eq buf (current-buffer))
2952           (message-bury buf)))
2953       (message-do-actions actions)
2954       (message-delete-frame frame org-frame)
2955       t)))
2956
2957 (defun message-dont-send ()
2958   "Don't send the message you have been editing.
2959 Instead, just auto-save the buffer and then bury it."
2960   (interactive)
2961   (message-save-drafts)
2962   (let ((actions message-postpone-actions)
2963         (frame (selected-frame))
2964         (org-frame message-original-frame))
2965     (message-bury (current-buffer))
2966     (message-do-actions actions)
2967     (message-delete-frame frame org-frame)))
2968
2969 (defun message-kill-buffer ()
2970   "Kill the current buffer."
2971   (interactive)
2972   (when (or (not (buffer-modified-p))
2973             (eq t message-kill-buffer-query-function)
2974             (funcall message-kill-buffer-query-function
2975                      "The buffer modified; kill anyway? "))
2976     (let ((actions message-kill-actions)
2977           (draft-article message-draft-article)
2978           (auto-save-file-name buffer-auto-save-file-name)
2979           (file-name buffer-file-name)
2980           (modified (buffer-modified-p))
2981           (frame (selected-frame))
2982           (org-frame message-original-frame))
2983       (setq buffer-file-name nil)
2984       (kill-buffer (current-buffer))
2985       (when (and message-kill-buffer-and-remove-file
2986                  (or (and auto-save-file-name
2987                           (file-exists-p auto-save-file-name))
2988                      (and file-name
2989                           (file-exists-p file-name)))
2990                  (yes-or-no-p (format "Remove the backup file%s? "
2991                                       (if modified " too" ""))))
2992         (ignore-errors
2993           (delete-file auto-save-file-name))
2994         (let ((message-draft-article draft-article))
2995           (message-disassociate-draft)))
2996       (message-do-actions actions)
2997       (message-delete-frame frame org-frame)))
2998   (message ""))
2999
3000 (defun message-mimic-kill-buffer ()
3001   "Kill the current buffer with query.  This is an imitation for
3002 `kill-buffer', but it will delete a message frame."
3003   (interactive)
3004   (let ((bufname (read-buffer (format "Kill buffer: (default %s) "
3005                                       (buffer-name))))
3006         message-kill-buffer-and-remove-file)
3007     (when (or (not bufname)
3008               (string-equal bufname "")
3009               (string-equal bufname (buffer-name)))
3010       (message-kill-buffer))))
3011
3012 (defun message-delete-frame (frame org-frame)
3013   "Delete frame for editing message."
3014   (when (and (or (static-if (featurep 'xemacs)
3015                      (device-on-window-system-p)
3016                    window-system)
3017                  (>= emacs-major-version 20))
3018              (or (and (eq message-delete-frame-on-exit t)
3019                       (select-frame frame)
3020                       (or (eq frame org-frame)
3021                           (prog1
3022                               (y-or-n-p "Delete this frame?")
3023                             (message ""))))
3024                  (and (eq message-delete-frame-on-exit 'ask)
3025                       (select-frame frame)
3026                       (prog1
3027                           (y-or-n-p "Delete this frame?")
3028                         (message "")))))
3029     (delete-frame frame)))
3030
3031 (defun message-bury (buffer)
3032   "Bury this mail BUFFER."
3033   (let ((newbuf (other-buffer buffer)))
3034     (bury-buffer buffer)
3035     (if (and (fboundp 'frame-parameters)
3036              (cdr (assq 'dedicated (frame-parameters)))
3037              (not (null (delq (selected-frame) (visible-frame-list)))))
3038         (delete-frame (selected-frame))
3039       (switch-to-buffer newbuf))))
3040
3041 (defun message-send (&optional arg)
3042   "Send the message in the current buffer.
3043 If `message-interactive' is non-nil, wait for success indication or
3044 error messages, and inform user.
3045 Otherwise any failure is reported in a message back to the user from
3046 the mailer.
3047 The usage of ARG is defined by the instance that called Message.
3048 It should typically alter the sending method in some way or other."
3049   (interactive "P")
3050   ;; Disabled test.
3051   (when (or (buffer-modified-p)
3052             (message-check-element 'unchanged)
3053             (y-or-n-p "No changes in the buffer; really send? "))
3054     ;; Make it possible to undo the coming changes.
3055     (undo-boundary)
3056     (let ((inhibit-read-only t))
3057       (put-text-property (point-min) (point-max) 'read-only nil))
3058     (run-hooks 'message-send-hook)
3059     (message-fix-before-sending)
3060     (message message-sending-message)
3061     (let ((message-encoding-buffer
3062            (message-generate-new-buffer-clone-locals " message encoding"))
3063           (message-edit-buffer (current-buffer))
3064           (message-mime-mode mime-edit-mode-flag)
3065           (alist message-send-method-alist)
3066           (success t)
3067           elem sent dont-barf-on-no-method
3068           (message-options message-options))
3069       (message-options-set-recipient)
3070       (save-excursion
3071         (set-buffer message-encoding-buffer)
3072         (erase-buffer)
3073         ;; ;; Avoid copying text props (except hard newlines).
3074         ;; T-gnus change: copy all text props from the editing buffer
3075         ;; into the encoding buffer.
3076         (insert-buffer-substring message-edit-buffer)
3077         (funcall message-encode-function)
3078         (while (and success
3079                     (setq elem (pop alist)))
3080           (when (funcall (cadr elem))
3081             (when (and (or (not (memq (car elem)
3082                                       message-sent-message-via))
3083                            (if (or (message-gnksa-enable-p 'multiple-copies)
3084                                    (not (eq (car elem) 'news)))
3085                                (y-or-n-p
3086                                 (format
3087                                  "Already sent message via %s; resend? "
3088                                  (car elem)))
3089                              (error "Denied posting -- multiple copies")))
3090                        (setq success (funcall (caddr elem) arg)))
3091               (setq sent t)))))
3092       (unless
3093           (or sent
3094               (not success)
3095               (let ((fcc (message-fetch-field "Fcc"))
3096                     (gcc (message-fetch-field "Gcc")))
3097                 (when (or fcc gcc)
3098                   (or (eq message-allow-no-recipients 'always)
3099                       (and (not (eq message-allow-no-recipients 'never))
3100                            (setq dont-barf-on-no-method
3101                                  (gnus-y-or-n-p
3102                                   (format "No receiver, perform %s anyway? "
3103                                           (cond ((and fcc gcc) "Fcc and Gcc")
3104                                                 (fcc "Fcc")
3105                                                 (t "Gcc"))))))))))
3106         (error "No methods specified to send by"))
3107       (prog1
3108           (when (or dont-barf-on-no-method
3109                     (and success sent))
3110             (message-do-fcc)
3111             (save-excursion
3112               (run-hooks 'message-sent-hook))
3113             (message "Sending...done")
3114             ;; Mark the buffer as unmodified and delete auto-save.
3115             (set-buffer-modified-p nil)
3116             (delete-auto-save-file-if-necessary t)
3117             (message-disassociate-draft)
3118             ;; Delete other mail buffers and stuff.
3119             (message-do-send-housekeeping)
3120             (message-do-actions message-send-actions)
3121             ;; Return success.
3122             t)
3123         (kill-buffer message-encoding-buffer)))))
3124
3125 (defun message-send-via-mail (arg)
3126   "Send the current message via mail."
3127   (message-send-mail arg))
3128
3129 (defun message-send-via-news (arg)
3130   "Send the current message via news."
3131   (message-send-news arg))
3132
3133 (defmacro message-check (type &rest forms)
3134   "Eval FORMS if TYPE is to be checked."
3135   `(or (message-check-element ,type)
3136        (save-excursion
3137          ,@forms)))
3138
3139 (put 'message-check 'lisp-indent-function 1)
3140 (put 'message-check 'edebug-form-spec '(form body))
3141
3142 ;; Advise the function `invisible-region'.
3143 (let (current-load-list)
3144   (eval
3145    `(defadvice invisible-region (around add-mime-edit-invisible (start end)
3146                                         activate)
3147       "Advised by T-gnus Message.
3148 Add the text property `mime-edit-invisible' to an invisible text when
3149 the buffer's major mode is `message-mode'.  The added property will be
3150 used to distinguish whether the invisible text is a MIME part or not."
3151       ,(if (featurep 'xemacs)
3152            '(if (eq ?\n (char-after start))
3153                 (setq start (1+ start)))
3154          '(if (eq ?\n (char-after (1- end)))
3155               (setq end (1- end))))
3156       (setq ad-return-value
3157             (if (eq 'message-mode major-mode)
3158                 (add-text-properties start end
3159                                      '(invisible t mime-edit-invisible t))
3160               (put-text-property start end 'invisible t))))))
3161
3162 (defun message-text-with-property (prop)
3163   "Return a list of all points where the text has PROP."
3164   (let ((points nil)
3165         (point (point-min)))
3166     (save-excursion
3167       (while (< point (point-max))
3168         (when (get-text-property point prop)
3169           (push point points))
3170         (incf point)))
3171     (nreverse points)))
3172
3173 (defun message-fix-before-sending ()
3174   "Do various things to make the message nice before sending it."
3175   ;; Make sure there's a newline at the end of the message.
3176   (widen)
3177   (goto-char (point-max))
3178   (unless (bolp)
3179     (insert "\n"))
3180   ;; Delete all invisible text except for the mime parts which might
3181   ;; be inserted by the MIME-Edit.
3182   (message-check 'invisible-text
3183     (let (from
3184           (to (point-min))
3185           mime-from mime-to hidden-start)
3186       (while (setq from (text-property-any to (point-max) 'invisible t))
3187         (setq to (or (text-property-not-all from (point-max) 'invisible t)
3188                      (point-max))
3189               mime-to from)
3190         (while (setq mime-from (text-property-any mime-to to
3191                                                   'mime-edit-invisible t))
3192           (when (> mime-from mime-to)
3193             (setq hidden-start (or hidden-start mime-to))
3194             (put-text-property mime-to mime-from 'invisible nil))
3195           (setq mime-to (or (text-property-not-all mime-from to
3196                                                    'mime-edit-invisible t)
3197                             to)))
3198         (when (< mime-to to)
3199           (setq hidden-start (or hidden-start mime-to))
3200           (put-text-property mime-to to 'invisible nil)))
3201       (when hidden-start
3202         (goto-char hidden-start)
3203         (set-window-start (selected-window) (gnus-point-at-bol))
3204         (unless (yes-or-no-p
3205                  "Invisible text found and made visible; continue posting? ")
3206           (error "Invisible text found and made visible")))))
3207   (message-check 'illegible-text
3208     (let ((mm-7bit-chars "\x20-\x7f\r\n\t\x7\x8\xb\xc\x1f\x1b")
3209           found choice)
3210       (message-goto-body)
3211       (skip-chars-forward mm-7bit-chars)
3212       (while (not (eobp))
3213         (when (let ((char (char-after)))
3214                 (or (< (mm-char-int char) 128)
3215                     (and (mm-multibyte-p)
3216                          (memq (char-charset char)
3217                                '(eight-bit-control eight-bit-graphic
3218                                                    control-1)))))
3219           (add-text-properties (point) (1+ (point)) '(highlight t))
3220           (setq found t))
3221         (forward-char)
3222         (skip-chars-forward mm-7bit-chars))
3223       (when found
3224         (setq choice
3225               (gnus-multiple-choice
3226                "Illegible text found. Continue posting? "
3227                '((?d "Remove and continue posting")
3228                  (?r "Replace with dots and continue posting")
3229                  (?i "Ignore and continue posting")
3230                  (?e "Continue editing"))))
3231         (if (eq choice ?e)
3232           (error "Illegible text found"))
3233         (message-goto-body)
3234         (skip-chars-forward mm-7bit-chars)
3235         (while (not (eobp))
3236           (when (let ((char (char-after)))
3237                   (or (< (mm-char-int char) 128)
3238                       (and (mm-multibyte-p)
3239                            (memq (char-charset char)
3240                                  '(eight-bit-control eight-bit-graphic
3241                                                      control-1)))))
3242             (if (eq choice ?i)
3243                 (remove-text-properties (point) (1+ (point)) '(highlight t))
3244               (delete-char 1)
3245               (if (eq choice ?r)
3246                   (insert "."))))
3247           (forward-char)
3248           (skip-chars-forward mm-7bit-chars))))))
3249
3250 (defun message-add-action (action &rest types)
3251   "Add ACTION to be performed when doing an exit of type TYPES."
3252   (while types
3253     (add-to-list (intern (format "message-%s-actions" (pop types)))
3254                  action)))
3255
3256 (defun message-delete-action (action &rest types)
3257   "Delete ACTION from lists of actions performed when doing an exit of type TYPES."
3258   (let (var)
3259     (while types
3260       (set (setq var (intern (format "message-%s-actions" (pop types))))
3261            (delq action (symbol-value var))))))
3262
3263 (defun message-do-actions (actions)
3264   "Perform all actions in ACTIONS."
3265   ;; Now perform actions on successful sending.
3266   (while actions
3267     (ignore-errors
3268       (cond
3269        ;; A simple function.
3270        ((message-functionp (car actions))
3271         (funcall (car actions)))
3272        ;; Something to be evaled.
3273        (t
3274         (eval (car actions)))))
3275     (pop actions)))
3276
3277 (defsubst message-maybe-split-and-send-mail ()
3278   "Split a message if necessary, and send it via mail.
3279 Returns nil if sending succeeded, returns any string if sending failed.
3280 This sub function is for exclusive use of `message-send-mail'."
3281   (let ((mime-edit-split-ignored-field-regexp
3282          mime-edit-split-ignored-field-regexp)
3283         (case-fold-search t)
3284         failure)
3285     (while (string-match "Message-ID" mime-edit-split-ignored-field-regexp)
3286       (setq mime-edit-split-ignored-field-regexp
3287             (concat (substring mime-edit-split-ignored-field-regexp
3288                                0 (match-beginning 0))
3289                     "Hey_MIME-Edit,_there_is_an_inviolable_Message_ID"
3290                     "_so_don't_rape_it!"
3291                     (substring mime-edit-split-ignored-field-regexp
3292                                (match-end 0)))))
3293     (setq failure
3294           (or
3295            (catch 'message-sending-mail-failure
3296              (mime-edit-maybe-split-and-send
3297               (function
3298                (lambda ()
3299                  (interactive)
3300                  (save-restriction
3301                    (std11-narrow-to-header mail-header-separator)
3302                    (goto-char (point-min))
3303                    (when (re-search-forward "^Message-ID:" nil t)
3304                      (delete-region (match-end 0) (std11-field-end))
3305                      (insert " " (message-make-message-id))))
3306                  (condition-case err
3307                      (funcall (or message-send-mail-real-function
3308                                   message-send-mail-function))
3309                    (error
3310                     (throw 'message-sending-mail-failure err))))))
3311              nil)
3312            (condition-case err
3313                (progn
3314                  (funcall (or message-send-mail-real-function
3315                               message-send-mail-function))
3316                  nil)
3317              (error err))))
3318     (when failure
3319       (if (eq 'error (car failure))
3320           (cadr failure)
3321         (prin1-to-string failure)))))
3322
3323 (defun message-send-mail-partially ()
3324   "Send mail as message/partial."
3325   ;; replace the header delimiter with a blank line
3326   (goto-char (point-min))
3327   (re-search-forward
3328    (concat "^" (regexp-quote mail-header-separator) "\n"))
3329   (replace-match "\n")
3330   (run-hooks 'message-send-mail-hook)
3331   (let ((p (goto-char (point-min)))
3332         (tembuf (message-generate-new-buffer-clone-locals " message temp"))
3333         (curbuf (current-buffer))
3334         (id (message-make-message-id)) (n 1)
3335         plist total  header required-mail-headers)
3336     (while (not (eobp))
3337       (if (< (point-max) (+ p message-send-mail-partially-limit))
3338           (goto-char (point-max))
3339         (goto-char (+ p message-send-mail-partially-limit))
3340         (beginning-of-line)
3341         (if (<= (point) p) (forward-line 1))) ;; In case of bad message.
3342       (push p plist)
3343       (setq p (point)))
3344     (setq total (length plist))
3345     (push (point-max) plist)
3346     (setq plist (nreverse plist))
3347     (unwind-protect
3348         (save-excursion
3349           (setq p (pop plist))
3350           (while plist
3351             (set-buffer curbuf)
3352             (copy-to-buffer tembuf p (car plist))
3353             (set-buffer tembuf)
3354             (goto-char (point-min))
3355             (if header
3356                 (progn
3357                   (goto-char (point-min))
3358                   (narrow-to-region (point) (point))
3359                   (insert header))
3360               (message-goto-eoh)
3361               (setq header (buffer-substring (point-min) (point)))
3362               (goto-char (point-min))
3363               (narrow-to-region (point) (point))
3364               (insert header)
3365               (message-remove-header "Mime-Version")
3366               (message-remove-header "Content-Type")
3367               (message-remove-header "Content-Transfer-Encoding")
3368               (message-remove-header "Message-ID")
3369               (message-remove-header "Lines")
3370               (goto-char (point-max))
3371               (insert "Mime-Version: 1.0\n")
3372               (setq header (buffer-substring (point-min) (point-max))))
3373             (goto-char (point-max))
3374             (insert (format "Content-Type: message/partial; id=\"%s\"; number=%d; total=%d\n\n"
3375                             id n total))
3376             (forward-char -1)
3377             (let ((mail-header-separator ""))
3378               (when (memq 'Message-ID message-required-mail-headers)
3379                 (insert "Message-ID: " (message-make-message-id) "\n"))
3380               (when (memq 'Lines message-required-mail-headers)
3381                 (insert "Lines: " (message-make-lines) "\n"))
3382               (message-goto-subject)
3383               (end-of-line)
3384               (insert (format " (%d/%d)" n total))
3385               (widen)
3386               (mm-with-unibyte-current-buffer
3387                 (funcall (or message-send-mail-real-function
3388                              message-send-mail-function))))
3389             (setq n (+ n 1))
3390             (setq p (pop plist))
3391             (erase-buffer)))
3392       (kill-buffer tembuf))))
3393
3394 (defun message-send-mail (&optional arg)
3395   (require 'mail-utils)
3396   (let* ((tembuf (message-generate-new-buffer-clone-locals " message temp"))
3397          (case-fold-search nil)
3398          (news (message-news-p))
3399          (message-this-is-mail t)
3400          (headers message-required-mail-headers)
3401          failure)
3402     (save-restriction
3403       (message-narrow-to-headers)
3404       ;; Generate the Mail-Followup-To header if the header is not there...
3405       (if (and (or message-subscribed-regexps
3406                    message-subscribed-addresses
3407                    message-subscribed-address-file
3408                    message-subscribed-address-functions)
3409                (not (mail-fetch-field "mail-followup-to")))
3410           (setq headers
3411                 (cons
3412                  (cons "Mail-Followup-To" (message-make-mft))
3413                  message-required-mail-headers))
3414         ;; otherwise, delete the MFT header if the field is empty
3415         (when (equal "" (mail-fetch-field "mail-followup-to"))
3416           (message-remove-header "^Mail-Followup-To:")))
3417       ;; Insert some headers.
3418       (let ((message-deletable-headers
3419              (if news nil message-deletable-headers)))
3420         (message-generate-headers headers))
3421       ;; Let the user do all of the above.
3422       (run-hooks 'message-header-hook))
3423     (if (not (message-check-mail-syntax))
3424         (progn
3425           (message "")
3426           nil)
3427       (unwind-protect
3428           (save-excursion
3429             (set-buffer tembuf)
3430             (erase-buffer)
3431             ;; ;; Avoid copying text props (except hard newlines).
3432             ;; T-gnus change: copy all text props from the editing buffer
3433             ;; into the encoding buffer.
3434             (insert-buffer-substring message-encoding-buffer)
3435             ;; Remove some headers.
3436             (save-restriction
3437               (message-narrow-to-headers)
3438 ;; We Semi-gnus people have no use for it.
3439 ;;            ;; We (re)generate the Lines header.
3440 ;;            (when (memq 'Lines message-required-mail-headers)
3441 ;;              (message-generate-headers '(Lines)))
3442               (message-remove-header message-ignored-mail-headers t))
3443             (goto-char (point-max))
3444             ;; require one newline at the end.
3445             (or (= (preceding-char) ?\n)
3446                 (insert ?\n))
3447             (when
3448                 (save-restriction
3449                   (message-narrow-to-headers)
3450                   (and news
3451                        (or (message-fetch-field "cc")
3452                            (message-fetch-field "to"))
3453                        (let ((ct (mime-read-Content-Type)))
3454                          (or (not ct)
3455                              (and (eq 'text (cdr (assq 'type ct)))
3456                                   (eq 'plain (cdr (assq 'subtype ct))))))))
3457               (message-insert-courtesy-copy))
3458             (setq failure (message-maybe-split-and-send-mail)))
3459         (kill-buffer tembuf))
3460       (set-buffer message-edit-buffer)
3461       (if failure
3462           (progn
3463             (message "Couldn't send message via mail: %s" failure)
3464             nil)
3465         (push 'mail message-sent-message-via)))))
3466
3467 (defun message-send-mail-with-sendmail ()
3468   "Send off the prepared buffer with sendmail."
3469   (let ((errbuf (if message-interactive
3470                     (message-generate-new-buffer-clone-locals
3471                      " sendmail errors")
3472                   0))
3473         resend-to-addresses delimline)
3474     (let ((case-fold-search t))
3475       (save-restriction
3476         (message-narrow-to-headers)
3477         (setq resend-to-addresses (message-fetch-field "resent-to")))
3478       ;; Change header-delimiter to be what sendmail expects.
3479       (goto-char (point-min))
3480       (re-search-forward
3481        (concat "^" (regexp-quote mail-header-separator) "\n"))
3482       (replace-match "\n")
3483       (backward-char 1)
3484       (setq delimline (point-marker))
3485       (run-hooks 'message-send-mail-hook)
3486       ;; Insert an extra newline if we need it to work around
3487       ;; Sun's bug that swallows newlines.
3488       (goto-char (1+ delimline))
3489       (when (eval message-mailer-swallows-blank-line)
3490         (newline))
3491       (when message-interactive
3492         (save-excursion
3493           (set-buffer errbuf)
3494           (erase-buffer))))
3495     (let ((default-directory "/"))
3496       (as-binary-process
3497        (apply 'call-process-region
3498               (append (list (point-min) (point-max)
3499                             (if (boundp 'sendmail-program)
3500                                 sendmail-program
3501                               "/usr/lib/sendmail")
3502                             nil errbuf nil "-oi")
3503                       ;; Always specify who from,
3504                       ;; since some systems have broken sendmails.
3505                       ;; But some systems are more broken with -f, so
3506                       ;; we'll let users override this.
3507                       (if (null message-sendmail-f-is-evil)
3508                           (list "-f" (message-make-address)))
3509                       ;; These mean "report errors by mail"
3510                       ;; and "deliver in background".
3511                       (if (null message-interactive) '("-oem" "-odb"))
3512                       ;; Get the addresses from the message
3513                       ;; unless this is a resend.
3514                       ;; We must not do that for a resend
3515                       ;; because we would find the original addresses.
3516                       ;; For a resend, include the specific addresses.
3517                       (if resend-to-addresses
3518                           (list resend-to-addresses)
3519                         '("-t"))))))
3520     (when message-interactive
3521       (save-excursion
3522         (set-buffer errbuf)
3523         (goto-char (point-min))
3524         (while (re-search-forward "\n\n* *" nil t)
3525           (replace-match "; "))
3526         (if (not (zerop (buffer-size)))
3527             (error "Sending...failed to %s"
3528                    (buffer-substring (point-min) (point-max)))))
3529       (when (bufferp errbuf)
3530         (kill-buffer errbuf)))))
3531
3532 (defun message-send-mail-with-qmail ()
3533   "Pass the prepared message buffer to qmail-inject.
3534 Refer to the documentation for the variable `message-send-mail-function'
3535 to find out how to use this."
3536   ;; replace the header delimiter with a blank line
3537   (goto-char (point-min))
3538   (re-search-forward
3539    (concat "^" (regexp-quote mail-header-separator) "\n"))
3540   (replace-match "\n")
3541   (backward-char 1)
3542   (run-hooks 'message-send-mail-hook)
3543   ;; send the message
3544   (case
3545       (as-binary-process
3546        (apply
3547         'call-process-region 1 (point-max) message-qmail-inject-program
3548         nil nil nil
3549         ;; qmail-inject's default behaviour is to look for addresses on the
3550         ;; command line; if there're none, it scans the headers.
3551         ;; yes, it does The Right Thing w.r.t. Resent-To and it's kin.
3552         ;;
3553         ;; in general, ALL of qmail-inject's defaults are perfect for simply
3554         ;; reading a formatted (i. e., at least a To: or Resent-To header)
3555         ;; message from stdin.
3556         ;;
3557         ;; qmail also has the advantage of not having been raped by
3558         ;; various vendors, so we don't have to allow for that, either --
3559         ;; compare this with message-send-mail-with-sendmail and weep
3560         ;; for sendmail's lost innocence.
3561         ;;
3562         ;; all this is way cool coz it lets us keep the arguments entirely
3563         ;; free for -inject-arguments -- a big win for the user and for us
3564         ;; since we don't have to play that double-guessing game and the user
3565         ;; gets full control (no gestapo'ish -f's, for instance).  --sj
3566         (if (functionp message-qmail-inject-args)
3567             (funcall message-qmail-inject-args)
3568           message-qmail-inject-args)))
3569     ;; qmail-inject doesn't say anything on it's stdout/stderr,
3570     ;; we have to look at the retval instead
3571     (0 nil)
3572     (100 (error "qmail-inject reported permanent failure"))
3573     (111 (error "qmail-inject reported transient failure"))
3574     ;; should never happen
3575     (t   (error "qmail-inject reported unknown failure"))))
3576
3577 (defun message-send-mail-with-mh ()
3578   "Send the prepared message buffer with mh."
3579   (let ((mh-previous-window-config nil)
3580         (name (mh-new-draft-name)))
3581     (setq buffer-file-name name)
3582     ;; MH wants to generate these headers itself.
3583     (when message-mh-deletable-headers
3584       (let ((headers message-mh-deletable-headers))
3585         (while headers
3586           (goto-char (point-min))
3587           (and (re-search-forward
3588                 (concat "^" (symbol-name (car headers)) ": *") nil t)
3589                (message-delete-line))
3590           (pop headers))))
3591     (run-hooks 'message-send-mail-hook)
3592     ;; Pass it on to mh.
3593     (mh-send-letter)))
3594
3595 (defun message-send-mail-with-smtp ()
3596   "Send off the prepared buffer with SMTP."
3597   (require 'smtp) ; XXX
3598   (let ((case-fold-search t)
3599         recipients)
3600     (save-restriction
3601       (message-narrow-to-headers)
3602       (setq recipients
3603             ;; XXX: Should be replaced by better one.
3604             (smtp-deduce-address-list (current-buffer)
3605                                       (point-min) (point-max)))
3606       ;; Remove BCC lines.
3607       (message-remove-header "bcc"))
3608     ;; replace the header delimiter with a blank line.
3609     (goto-char (point-min))
3610     (re-search-forward
3611      (concat "^" (regexp-quote mail-header-separator) "\n"))
3612     (replace-match "\n")
3613     (backward-char 1)
3614     (run-hooks 'message-send-mail-hook)
3615     (if recipients
3616         (static-if (fboundp 'smtp-send-buffer)
3617             (smtp-send-buffer user-mail-address recipients
3618                               (current-buffer))
3619           (let ((result (smtp-via-smtp user-mail-address recipients
3620                                        (current-buffer))))
3621             (unless (eq result t)
3622               (error "Sending failed; %s" result))))
3623       (error "Sending failed; no recipients"))))
3624
3625 (defsubst message-maybe-split-and-send-news (method)
3626   "Split a message if necessary, and send it via news.
3627 Returns nil if sending succeeded, returns t if sending failed.
3628 This sub function is for exclusive use of `message-send-news'."
3629   (let ((mime-edit-split-ignored-field-regexp
3630          mime-edit-split-ignored-field-regexp)
3631         (case-fold-search t))
3632     (while (string-match "Message-ID" mime-edit-split-ignored-field-regexp)
3633       (setq mime-edit-split-ignored-field-regexp
3634             (concat (substring mime-edit-split-ignored-field-regexp
3635                                0 (match-beginning 0))
3636                     "Hey_MIME-Edit,_there_is_an_inviolable_Message_ID"
3637                     "_so_don't_rape_it!"
3638                     (substring mime-edit-split-ignored-field-regexp
3639                                (match-end 0)))))
3640     (or
3641      (catch 'message-sending-news-failure
3642        (mime-edit-maybe-split-and-send
3643         (function
3644          (lambda ()
3645            (interactive)
3646            (save-restriction
3647              (std11-narrow-to-header mail-header-separator)
3648              (goto-char (point-min))
3649              (when (re-search-forward "^Message-ID:" nil t)
3650                (delete-region (match-end 0) (std11-field-end))
3651                (insert " " (message-make-message-id))))
3652            (unless (funcall message-send-news-function method)
3653              (throw 'message-sending-news-failure t)))))
3654        nil)
3655      (not (funcall message-send-news-function method)))))
3656
3657 (defun message-canlock-generate ()
3658   "Return a string that is non-trival to guess.
3659 Do not use this for anything important, it is cryptographically weak."
3660   (sha1 (concat (message-unique-id)
3661                 (format "%x%x%x" (random) (random t) (random))
3662                 (prin1-to-string (recent-keys))
3663                 (prin1-to-string (garbage-collect)))))
3664
3665 (defun message-canlock-password ()
3666   "The password used by message for cancel locks.
3667 This is the value of `canlock-password', if that option is non-nil.
3668 Otherwise, generate and save a value for `canlock-password' first."
3669   (unless canlock-password
3670     (customize-save-variable 'canlock-password (message-canlock-generate)))
3671   canlock-password)
3672
3673 (defun message-insert-canlock ()
3674   (when message-insert-canlock
3675     (message-canlock-password)
3676     (canlock-insert-header)))
3677
3678 (defun message-send-news (&optional arg)
3679   (let* ((tembuf (message-generate-new-buffer-clone-locals " *message temp*"))
3680          (case-fold-search nil)
3681          (method (if (message-functionp message-post-method)
3682                      (funcall message-post-method arg)
3683                    message-post-method))
3684          (newsgroups-field (save-restriction
3685                              (message-narrow-to-headers-or-head)
3686                              (message-fetch-field "Newsgroups")))
3687          (followup-field (save-restriction
3688                            (message-narrow-to-headers-or-head)
3689                            (message-fetch-field "Followup-To")))
3690          ;; BUG: We really need to get the charset for each name in the
3691          ;; Newsgroups and Followup-To lines to allow crossposting
3692          ;; between group namess with incompatible character sets.
3693          ;; -- Per Abrahamsen <abraham@dina.kvl.dk> 2001-10-08.
3694          (group-field-charset
3695           (gnus-group-name-charset method newsgroups-field))
3696          (followup-field-charset
3697           (gnus-group-name-charset method (or followup-field "")))
3698          (mime-field-encoding-method-alist
3699           (append (when group-field-charset
3700                     (list (cons "Newsgroups" group-field-charset)))
3701                   (when followup-field-charset
3702                     (list (cons "Followup-To" followup-field-charset)))
3703                   mime-field-encoding-method-alist))
3704          (message-syntax-checks
3705           (if (and arg
3706                    (listp message-syntax-checks))
3707               (cons '(existing-newsgroups . disabled)
3708                     message-syntax-checks)
3709             message-syntax-checks))
3710          (message-this-is-news t)
3711          result)
3712     (save-restriction
3713       (message-narrow-to-headers)
3714       ;; Insert some headers.
3715       (message-generate-headers message-required-news-headers)
3716       (message-insert-canlock)
3717       ;; Let the user do all of the above.
3718       (run-hooks 'message-header-hook))
3719     ;; Note: This check will be disabled by the ".*" default value for
3720     ;; gnus-group-name-charset-group-alist. -- Pa 2001-10-07.
3721     (when (and group-field-charset
3722                (listp message-syntax-checks))
3723       (setq message-syntax-checks
3724             (cons '(valid-newsgroups . disabled)
3725                   message-syntax-checks)))
3726     (message-cleanup-headers)
3727     (if (not (let ((message-post-method method))
3728                (message-check-news-syntax)))
3729         nil
3730       (unwind-protect
3731           (save-excursion
3732             (set-buffer tembuf)
3733             (buffer-disable-undo)
3734             (erase-buffer)
3735             (insert-buffer-substring message-encoding-buffer)
3736             ;; Remove some headers.
3737             (save-restriction
3738               (message-narrow-to-headers)
3739 ;; We Semi-gnus people have no use for it.
3740 ;;            ;; We (re)generate the Lines header.
3741 ;;            (when (memq 'Lines message-required-mail-headers)
3742 ;;              (message-generate-headers '(Lines)))
3743               ;; Remove some headers.
3744               (message-remove-header message-ignored-news-headers t))
3745             (goto-char (point-max))
3746             ;; require one newline at the end.
3747             (or (= (preceding-char) ?\n)
3748                 (insert ?\n))
3749             (setq result (message-maybe-split-and-send-news method)))
3750         (kill-buffer tembuf))
3751       (set-buffer message-edit-buffer)
3752       (if result
3753           (progn
3754             (message "Couldn't send message via news: %s"
3755                      (nnheader-get-report (car method)))
3756             nil)
3757         (push 'news message-sent-message-via)))))
3758
3759 ;; 1997-09-29 by MORIOKA Tomohiko
3760 (defun message-send-news-with-gnus (method)
3761   (let ((case-fold-search t))
3762     ;; Remove the delimiter.
3763     (goto-char (point-min))
3764     (re-search-forward
3765      (concat "^" (regexp-quote mail-header-separator) "\n"))
3766     (replace-match "\n")
3767     (backward-char 1)
3768     (run-hooks 'message-send-news-hook)
3769     (gnus-open-server method)
3770     (message "Sending news via %s..." (gnus-server-string method))
3771     (gnus-request-post method)
3772     ))
3773
3774 ;;;
3775 ;;; Header generation & syntax checking.
3776 ;;;
3777
3778 (defun message-check-element (type)
3779   "Return non-nil if this TYPE is not to be checked."
3780   (if (eq message-syntax-checks 'dont-check-for-anything-just-trust-me)
3781       t
3782     (let ((able (assq type message-syntax-checks)))
3783       (and (consp able)
3784            (eq (cdr able) 'disabled)))))
3785
3786 (defun message-check-news-syntax ()
3787   "Check the syntax of the message."
3788   (save-excursion
3789     (save-restriction
3790       (widen)
3791       (and
3792        ;; We narrow to the headers and check them first.
3793        (save-excursion
3794          (save-restriction
3795            (message-narrow-to-headers)
3796            (message-check-news-header-syntax)))
3797        ;; Check the body.
3798        (save-excursion
3799          (set-buffer message-edit-buffer)
3800          (message-check-news-body-syntax))))))
3801
3802 (defun message-check-news-header-syntax ()
3803   (and
3804    ;; Check Newsgroups header.
3805    (message-check 'newsgroups
3806      (let ((group (message-fetch-field "newsgroups")))
3807        (or
3808         (and group
3809              (not (string-match "\\`[ \t]*\\'" group)))
3810         (ignore
3811          (message
3812           "The newsgroups field is empty or missing.  Posting is denied.")))))
3813    ;; Check the Subject header.
3814    (message-check 'subject
3815      (let* ((case-fold-search t)
3816             (subject (message-fetch-field "subject")))
3817        (or
3818         (and subject
3819              (not (string-match "\\`[ \t]*\\'" subject)))
3820         (ignore
3821          (message
3822           "The subject field is empty or missing.  Posting is denied.")))))
3823    ;; Check for commands in Subject.
3824    (message-check 'subject-cmsg
3825      (if (string-match "^cmsg " (message-fetch-field "subject"))
3826          (y-or-n-p
3827           "The control code \"cmsg\" is in the subject.  Really post? ")
3828        t))
3829    ;; Check for multiple identical headers.
3830    (message-check 'multiple-headers
3831      (let (found)
3832        (while (and (not found)
3833                    (re-search-forward "^[^ \t:]+: " nil t))
3834          (save-excursion
3835            (or (re-search-forward
3836                 (concat "^"
3837                         (regexp-quote
3838                          (setq found
3839                                (buffer-substring
3840                                 (match-beginning 0) (- (match-end 0) 2))))
3841                         ":")
3842                 nil t)
3843                (setq found nil))))
3844        (if found
3845            (y-or-n-p (format "Multiple %s headers.  Really post? " found))
3846          t)))
3847    ;; Check for Version and Sendsys.
3848    (message-check 'sendsys
3849      (if (re-search-forward "^Sendsys:\\|^Version:" nil t)
3850          (y-or-n-p
3851           (format "The article contains a %s command.  Really post? "
3852                   (buffer-substring (match-beginning 0)
3853                                     (1- (match-end 0)))))
3854        t))
3855    ;; See whether we can shorten Followup-To.
3856    (message-check 'shorten-followup-to
3857      (let ((newsgroups (message-fetch-field "newsgroups"))
3858            (followup-to (message-fetch-field "followup-to"))
3859            to)
3860        (when (and newsgroups
3861                   (string-match "," newsgroups)
3862                   (not followup-to)
3863                   (not
3864                    (zerop
3865                     (length
3866                      (setq to (completing-read
3867                                "Followups to (default: no Followup-To header) "
3868                                (mapcar (lambda (g) (list g))
3869                                        (cons "poster"
3870                                              (message-tokenize-header
3871                                               newsgroups)))))))))
3872          (goto-char (point-min))
3873          (insert "Followup-To: " to "\n"))
3874        t))
3875    ;; Check "Shoot me".
3876    (message-check 'shoot
3877      (if (re-search-forward
3878           "Message-ID.*.i-did-not-set--mail-host-address--so-shoot-me" nil t)
3879          (y-or-n-p "You appear to have a misconfigured system.  Really post? ")
3880        t))
3881    ;; Check for Approved.
3882    (message-check 'approved
3883      (if (re-search-forward "^Approved:" nil t)
3884          (y-or-n-p "The article contains an Approved header.  Really post? ")
3885        t))
3886    ;; Check the Message-ID header.
3887    (message-check 'message-id
3888      (let* ((case-fold-search t)
3889             (message-id (message-fetch-field "message-id" t)))
3890        (or (not message-id)
3891            ;; Is there an @ in the ID?
3892            (and (string-match "@" message-id)
3893                 ;; Is there a dot in the ID?
3894                 (string-match "@[^.]*\\." message-id)
3895                 ;; Does the ID end with a dot?
3896                 (not (string-match "\\.>" message-id)))
3897            (y-or-n-p
3898             (format "The Message-ID looks strange: \"%s\".  Really post? "
3899                     message-id)))))
3900    ;; Check the Newsgroups & Followup-To headers.
3901    (message-check 'existing-newsgroups
3902      (let* ((case-fold-search t)
3903             (newsgroups (message-fetch-field "newsgroups"))
3904             (followup-to (message-fetch-field "followup-to"))
3905             (groups (message-tokenize-header
3906                      (if followup-to
3907                          (concat newsgroups "," followup-to)
3908                        newsgroups)))
3909             (post-method (if (message-functionp message-post-method)
3910                              (funcall message-post-method)
3911                            message-post-method))
3912             ;; KLUDGE to handle nnvirtual groups.  Doing this right
3913             ;; would probably involve a new nnoo function.
3914             ;; -- Per Abrahamsen <abraham@dina.kvl.dk>, 2001-10-17.
3915             (method (if (and (consp post-method)
3916                              (eq (car post-method) 'nnvirtual)
3917                              gnus-message-group-art)
3918                         (let ((group (car (nnvirtual-find-group-art
3919                                            (car gnus-message-group-art)
3920                                            (cdr gnus-message-group-art)))))
3921                           (gnus-find-method-for-group group))
3922                       post-method))
3923             (known-groups
3924              (mapcar (lambda (n)
3925                        (gnus-group-name-decode
3926                         (gnus-group-real-name n)
3927                         (gnus-group-name-charset method n)))
3928                      (gnus-groups-from-server method)))
3929             errors)
3930        (while groups
3931          (unless (or (equal (car groups) "poster")
3932                      (member (car groups) known-groups))
3933            (push (car groups) errors))
3934          (pop groups))
3935        (cond
3936         ;; Gnus is not running.
3937         ((or (not (and (boundp 'gnus-active-hashtb)
3938                        gnus-active-hashtb))
3939              (not (boundp 'gnus-read-active-file)))
3940          t)
3941         ;; We don't have all the group names.
3942         ((and (or (not gnus-read-active-file)
3943                   (eq gnus-read-active-file 'some))
3944               errors)
3945          (y-or-n-p
3946           (format
3947            "Really post to %s possibly unknown group%s: %s? "
3948            (if (= (length errors) 1) "this" "these")
3949            (if (= (length errors) 1) "" "s")
3950            (mapconcat 'identity errors ", "))))
3951         ;; There were no errors.
3952         ((not errors)
3953          t)
3954         ;; There are unknown groups.
3955         (t
3956          (y-or-n-p
3957           (format
3958            "Really post to %s unknown group%s: %s? "
3959            (if (= (length errors) 1) "this" "these")
3960            (if (= (length errors) 1) "" "s")
3961            (mapconcat 'identity errors ", ")))))))
3962    ;; Check the Newsgroups & Followup-To headers for syntax errors.
3963    (message-check 'valid-newsgroups
3964      (let ((case-fold-search t)
3965            (headers '("Newsgroups" "Followup-To"))
3966            header error)
3967        (while (and headers (not error))
3968          (when (setq header (mail-fetch-field (car headers)))
3969            (if (or
3970                 (not
3971                  (string-match
3972                   "\\`\\([-+_&.a-zA-Z0-9]+\\)?\\(,[-+_&.a-zA-Z0-9]+\\)*\\'"
3973                   header))
3974                 (memq
3975                  nil (mapcar
3976                       (lambda (g)
3977                         (not (string-match "\\.\\'\\|\\.\\." g)))
3978                       (message-tokenize-header header ","))))
3979                (setq error t)))
3980          (unless error
3981            (pop headers)))
3982        (if (not error)
3983            t
3984          (y-or-n-p
3985           (format "The %s header looks odd: \"%s\".  Really post? "
3986                   (car headers) header)))))
3987    (message-check 'repeated-newsgroups
3988      (let ((case-fold-search t)
3989            (headers '("Newsgroups" "Followup-To"))
3990            header error groups group)
3991        (while (and headers
3992                    (not error))
3993          (when (setq header (mail-fetch-field (pop headers)))
3994            (setq groups (message-tokenize-header header ","))
3995            (while (setq group (pop groups))
3996              (when (member group groups)
3997                (setq error group
3998                      groups nil)))))
3999        (if (not error)
4000            t
4001          (y-or-n-p
4002           (format "Group %s is repeated in headers.  Really post? " error)))))
4003    ;; Check the From header.
4004    (message-check 'from
4005      (let* ((case-fold-search t)
4006             (from (message-fetch-field "from"))
4007             ad)
4008        (cond
4009         ((not from)
4010          (message "There is no From line.  Posting is denied.")
4011          nil)
4012         ((or (not (string-match
4013                    "@[^\\.]*\\."
4014                    (setq ad (nth 1 (mail-extract-address-components
4015                                     from))))) ;larsi@ifi
4016              (string-match "\\.\\." ad) ;larsi@ifi..uio
4017              (string-match "@\\." ad)   ;larsi@.ifi.uio
4018              (string-match "\\.$" ad)   ;larsi@ifi.uio.
4019              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
4020              (string-match "(.*).*(.*)" from)) ;(lars) (lars)
4021          (message
4022           "Denied posting -- the From looks strange: \"%s\"." from)
4023          nil)
4024         ((let ((addresses (rfc822-addresses from)))
4025            (while (and addresses
4026                        (not (eq (string-to-char (car addresses)) ?\()))
4027              (setq addresses (cdr addresses)))
4028            addresses)
4029          (message
4030           "Denied posting -- bad From address: \"%s\"." from)
4031          nil)
4032         (t t))))
4033    ;; Check the Reply-To header.
4034    (message-check 'reply-to
4035      (let* ((case-fold-search t)
4036             (reply-to (message-fetch-field "reply-to"))
4037             ad)
4038        (cond
4039         ((not reply-to)
4040          t)
4041         ((string-match "," reply-to)
4042          (y-or-n-p
4043           (format "Multiple Reply-To addresses: \"%s\". Really post? "
4044                   reply-to)))
4045         ((or (not (string-match
4046                    "@[^\\.]*\\."
4047                    (setq ad (nth 1 (mail-extract-address-components
4048                                     reply-to))))) ;larsi@ifi
4049              (string-match "\\.\\." ad) ;larsi@ifi..uio
4050              (string-match "@\\." ad)   ;larsi@.ifi.uio
4051              (string-match "\\.$" ad)   ;larsi@ifi.uio.
4052              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
4053              (string-match "(.*).*(.*)" reply-to)) ;(lars) (lars)
4054          (y-or-n-p
4055           (format
4056            "The Reply-To looks strange: \"%s\". Really post? "
4057            reply-to)))
4058         (t t))))))
4059
4060 (defun message-check-news-body-syntax ()
4061   (and
4062    ;; Check for long lines.
4063    (message-check 'long-lines
4064      (goto-char (point-min))
4065      (re-search-forward
4066       (concat "^" (regexp-quote mail-header-separator) "$"))
4067      (forward-line 1)
4068      (while (and
4069              (or (looking-at
4070                   mime-edit-tag-regexp)
4071                  (let ((p (point)))
4072                    (end-of-line)
4073                    (< (- (point) p) 80)))
4074              (zerop (forward-line 1))))
4075      (or (bolp)
4076          (eobp)
4077          (y-or-n-p
4078           "You have lines longer than 79 characters.  Really post? ")))
4079    ;; Check whether the article is empty.
4080    (message-check 'empty
4081      (goto-char (point-min))
4082      (re-search-forward
4083       (concat "^" (regexp-quote mail-header-separator) "$"))
4084      (forward-line 1)
4085      (let ((b (point)))
4086        (goto-char (point-max))
4087        (re-search-backward message-signature-separator nil t)
4088        (beginning-of-line)
4089        (or (re-search-backward "[^ \n\t]" b t)
4090            (if (message-gnksa-enable-p 'empty-article)
4091                (y-or-n-p "Empty article.  Really post? ")
4092              (message "Denied posting -- Empty article.")
4093              nil))))
4094    ;; Check for control characters.
4095    (message-check 'control-chars
4096      (if (re-search-forward "[\000-\007\013\015-\032\034-\037\200-\237]" nil t)
4097          (y-or-n-p
4098           "The article contains control characters.  Really post? ")
4099        t))
4100    ;; Check 8bit characters.
4101    (message-check '8bit
4102      (message-check-8bit))
4103    ;; Check excessive size.
4104    (message-check 'size
4105      (if (> (buffer-size) 60000)
4106          (y-or-n-p
4107           (format "The article is %d octets long.  Really post? "
4108                   (buffer-size)))
4109        t))
4110    ;; Check whether any new text has been added.
4111    (message-check 'new-text
4112      (or
4113       (not message-checksum)
4114       (not (eq (message-checksum) message-checksum))
4115       (if (message-gnksa-enable-p 'quoted-text-only)
4116           (y-or-n-p
4117            "It looks like no new text has been added.  Really post? ")
4118         (message "Denied posting -- no new text has been added.")
4119         nil)))
4120    ;; Check the length of the signature.
4121    (message-check 'signature
4122      (goto-char (point-max))
4123      (if (> (count-lines (point) (point-max)) 5)
4124          (y-or-n-p
4125           (format
4126            "Your .sig is %d lines; it should be max 4.  Really post? "
4127            (1- (count-lines (point) (point-max)))))
4128        t))
4129    ;; Ensure that text follows last quoted portion.
4130    (message-check 'quoting-style
4131      (goto-char (point-max))
4132      (let ((no-problem t))
4133        (when (search-backward-regexp "^>[^\n]*\n" nil t)
4134          (setq no-problem (search-forward-regexp "^[ \t]*[^>\n]" nil t)))
4135        (if no-problem
4136            t
4137          (if (message-gnksa-enable-p 'quoted-text-only)
4138              (y-or-n-p "Your text should follow quoted text.  Really post? ")
4139            ;; Ensure that
4140            (goto-char (point-min))
4141            (re-search-forward
4142             (concat "^" (regexp-quote mail-header-separator) "$"))
4143            (if (search-forward-regexp "^[ \t]*[^>\n]" nil t)
4144                (y-or-n-p "Your text should follow quoted text.  Really post? ")
4145              (message "Denied posting -- only quoted text.")
4146              nil)))))))
4147
4148 (defun message-check-mail-syntax ()
4149   "Check the syntax of the message."
4150   (save-excursion
4151     (save-restriction
4152       (widen)
4153       (and
4154        ;; We narrow to the headers and check them first.
4155        (save-excursion
4156          (save-restriction
4157            (message-narrow-to-headers)
4158            (message-check-mail-header-syntax)))
4159        ;; Check the body.
4160        (save-excursion
4161          (set-buffer message-edit-buffer)
4162          (message-check-mail-body-syntax))))))
4163
4164 (defun message-check-mail-header-syntax ()
4165   t)
4166
4167 (defun message-check-mail-body-syntax ()
4168   (and
4169    ;; Check 8bit characters.
4170    (message-check '8bit
4171      (message-check-8bit)
4172      )))
4173
4174 (defun message-check-8bit ()
4175   "Check the article contains 8bit characters."
4176   (save-excursion
4177     (set-buffer message-encoding-buffer)
4178     (message-narrow-to-headers)
4179     (let* ((case-fold-search t)
4180            (field-value (message-fetch-field "content-transfer-encoding")))
4181       (if (and field-value
4182                (member (downcase field-value) message-8bit-encoding-list))
4183           t
4184         (widen)
4185         (set-buffer (get-buffer-create " message syntax"))
4186         (erase-buffer)
4187         (goto-char (point-min))
4188         (set-buffer-multibyte nil)
4189         (insert-buffer-substring message-encoding-buffer)
4190         (goto-char (point-min))
4191         (if (re-search-forward "[^\x00-\x7f]" nil t)
4192             (y-or-n-p
4193              "The article contains 8bit characters.  Really post? ")
4194           t)))))
4195
4196 (defun message-checksum ()
4197   "Return a \"checksum\" for the current buffer."
4198   (let ((sum 0))
4199     (save-excursion
4200       (goto-char (point-min))
4201       (re-search-forward
4202        (concat "^" (regexp-quote mail-header-separator) "$"))
4203       (while (not (eobp))
4204         (when (not (looking-at "[ \t\n]"))
4205           (setq sum (logxor (ash sum 1) (if (natnump sum) 0 1)
4206                             (char-after))))
4207         (forward-char 1)))
4208     sum))
4209
4210 (defun message-do-fcc ()
4211   "Process Fcc headers in the current buffer."
4212   (let ((case-fold-search t)
4213         (coding-system-for-write 'raw-text)
4214         (output-coding-system 'raw-text)
4215         list file
4216         (mml-externalize-attachments message-fcc-externalize-attachments))
4217     (save-excursion
4218       (save-restriction
4219         (message-narrow-to-headers)
4220         (setq file (message-fetch-field "fcc" t)))
4221       (when file
4222         (set-buffer (get-buffer-create " *message temp*"))
4223         (erase-buffer)
4224         (insert-buffer-substring message-encoding-buffer)
4225         (save-restriction
4226           (message-narrow-to-headers)
4227           (while (setq file (message-fetch-field "fcc"))
4228             (push file list)
4229             (message-remove-header "fcc" nil t)))
4230         (goto-char (point-min))
4231         (when (re-search-forward
4232                (concat "^" (regexp-quote mail-header-separator) "$")
4233                nil t)
4234           (replace-match "" t t))
4235         ;; Process FCC operations.
4236         (while list
4237           (setq file (pop list))
4238           (if (string-match "^[ \t]*|[ \t]*\\(.*\\)[ \t]*$" file)
4239               ;; Pipe the article to the program in question.
4240               (call-process-region (point-min) (point-max) shell-file-name
4241                                    nil nil nil shell-command-switch
4242                                    (match-string 1 file))
4243             ;; Save the article.
4244             (setq file (expand-file-name file))
4245             (unless (file-exists-p (file-name-directory file))
4246               (make-directory (file-name-directory file) t))
4247             (if (and message-fcc-handler-function
4248                      (not (eq message-fcc-handler-function 'rmail-output)))
4249                 (funcall message-fcc-handler-function file)
4250               (if (and (file-readable-p file) (mail-file-babyl-p file))
4251                   (rmail-output file 1 nil t)
4252                 (let ((mail-use-rfc822 t))
4253                   (rmail-output file 1 t t))))))
4254         (kill-buffer (current-buffer))))))
4255
4256 (defun message-output (filename)
4257   "Append this article to Unix/babyl mail file FILENAME."
4258   (if (and (file-readable-p filename)
4259            (mail-file-babyl-p filename))
4260       (gnus-output-to-rmail filename t)
4261     (gnus-output-to-mail filename t)))
4262
4263 (defun message-cleanup-headers ()
4264   "Do various automatic cleanups of the headers."
4265   ;; Remove empty lines in the header.
4266   (save-restriction
4267     (message-narrow-to-headers)
4268     ;; Remove blank lines.
4269     (while (re-search-forward "^[ \t]*\n" nil t)
4270       (replace-match "" t t))
4271
4272     ;; Correct Newsgroups and Followup-To headers:  Change sequence of
4273     ;; spaces to comma and eliminate spaces around commas.  Eliminate
4274     ;; embedded line breaks.
4275     (goto-char (point-min))
4276     (while (re-search-forward "^\\(Newsgroups\\|Followup-To\\): +" nil t)
4277       (save-restriction
4278         (narrow-to-region
4279          (point)
4280          (if (re-search-forward "^[^ \t]" nil t)
4281              (match-beginning 0)
4282            (forward-line 1)
4283            (point)))
4284         (goto-char (point-min))
4285         (while (re-search-forward "\n[ \t]+" nil t)
4286           (replace-match " " t t))      ;No line breaks (too confusing)
4287         (goto-char (point-min))
4288         (while (re-search-forward "[ \t\n]*,[ \t\n]*\\|[ \t]+" nil t)
4289           (replace-match "," t t))
4290         (goto-char (point-min))
4291         ;; Remove trailing commas.
4292         (when (re-search-forward ",+$" nil t)
4293           (replace-match "" t t))))))
4294
4295 (defun message-make-date (&optional now)
4296   "Make a valid data header.
4297 If NOW, use that time instead."
4298   (let* ((now (or now (current-time)))
4299          (zone (nth 8 (decode-time now)))
4300          (sign "+"))
4301     (when (< zone 0)
4302       (setq sign "-")
4303       (setq zone (- zone)))
4304     (concat
4305      ;; The day name of the %a spec is locale-specific.  Pfff.
4306      (format "%s, " (capitalize (car (rassoc (nth 6 (decode-time now))
4307                                              parse-time-weekdays))))
4308      (format-time-string "%d" now)
4309      ;; The month name of the %b spec is locale-specific.  Pfff.
4310      (format " %s "
4311              (capitalize (car (rassoc (nth 4 (decode-time now))
4312                                       parse-time-months))))
4313      (format-time-string "%Y %H:%M:%S " now)
4314      ;; We do all of this because XEmacs doesn't have the %z spec.
4315      (format "%s%02d%02d" sign (/ zone 3600) (/ (% zone 3600) 60)))))
4316
4317 (defun message-make-followup-subject (subject)
4318   "Make a followup Subject."
4319   (cond
4320    ((and (eq message-use-subject-re 'guess)
4321          (string-match message-subject-encoded-re-regexp subject))
4322     subject)
4323    (message-use-subject-re
4324     (concat "Re: " (message-strip-subject-re subject)))
4325    (t subject)))
4326
4327 (defun message-make-message-id ()
4328   "Make a unique Message-ID."
4329   (concat "<" (message-unique-id)
4330           (let ((psubject (save-excursion (message-fetch-field "subject")))
4331                 (psupersedes
4332                  (save-excursion (message-fetch-field "supersedes"))))
4333             (if (or
4334                  (and message-reply-headers
4335                       (mail-header-references message-reply-headers)
4336                       (mail-header-subject message-reply-headers)
4337                       psubject
4338                       (not (string=
4339                             (message-strip-subject-re
4340                              (mail-header-subject message-reply-headers))
4341                             (message-strip-subject-re psubject))))
4342                  (and psupersedes
4343                       (string-match "_-_@" psupersedes)))
4344                 "_-_" ""))
4345           "@" (message-make-fqdn) ">"))
4346
4347 (defvar message-unique-id-char nil)
4348
4349 ;; If you ever change this function, make sure the new version
4350 ;; cannot generate IDs that the old version could.
4351 ;; You might for example insert a "." somewhere (not next to another dot
4352 ;; or string boundary), or modify the "fsf" string.
4353 (defun message-unique-id ()
4354   ;; Don't use microseconds from (current-time), they may be unsupported.
4355   ;; Instead we use this randomly inited counter.
4356   (setq message-unique-id-char
4357         (% (1+ (or message-unique-id-char (logand (random t) (1- (lsh 1 20)))))
4358            ;; (current-time) returns 16-bit ints,
4359            ;; and 2^16*25 just fits into 4 digits i base 36.
4360            (* 25 25)))
4361   (let ((tm (current-time)))
4362     (concat
4363      (if (memq system-type '(ms-dos emx vax-vms))
4364          (let ((user (downcase (user-login-name))))
4365            (while (string-match "[^a-z0-9_]" user)
4366              (aset user (match-beginning 0) ?_))
4367            user)
4368        (message-number-base36 (user-uid) -1))
4369      (message-number-base36 (+ (car tm)
4370                                (lsh (% message-unique-id-char 25) 16)) 4)
4371      (message-number-base36 (+ (nth 1 tm)
4372                                (lsh (/ message-unique-id-char 25) 16)) 4)
4373      ;; Append the newsreader name, because while the generated
4374      ;; ID is unique to this newsreader, other newsreaders might
4375      ;; otherwise generate the same ID via another algorithm.
4376      ".fsf")))
4377
4378 (defun message-number-base36 (num len)
4379   (if (if (< len 0)
4380           (<= num 0)
4381         (= len 0))
4382       ""
4383     (concat (message-number-base36 (/ num 36) (1- len))
4384             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
4385                                   (% num 36))))))
4386
4387 (defun message-make-organization ()
4388   "Make an Organization header."
4389   (let* ((organization
4390           (when message-user-organization
4391             (if (message-functionp message-user-organization)
4392                 (funcall message-user-organization)
4393               message-user-organization))))
4394     (save-excursion
4395       (message-set-work-buffer)
4396       (cond ((stringp organization)
4397              (insert organization))
4398             ((and (eq t organization)
4399                   message-user-organization-file
4400                   (file-exists-p message-user-organization-file))
4401              (insert-file-contents message-user-organization-file)))
4402       (goto-char (point-min))
4403       (while (re-search-forward "[\t\n]+" nil t)
4404         (replace-match "" t t))
4405       (unless (zerop (buffer-size))
4406         (buffer-string)))))
4407
4408 (defun message-make-lines ()
4409   "Count the number of lines and return numeric string."
4410   (save-excursion
4411     (save-restriction
4412       (widen)
4413       (message-goto-body)
4414       (int-to-string (count-lines (point) (point-max))))))
4415
4416 (defun message-make-in-reply-to ()
4417   "Return the In-Reply-To header for this message."
4418   (when message-reply-headers
4419     (let ((from (mail-header-from message-reply-headers))
4420           (date (mail-header-date message-reply-headers))
4421           (msg-id (mail-header-message-id message-reply-headers)))
4422       (when msg-id
4423         (concat msg-id
4424                 (when from
4425                   (let ((pair (std11-extract-address-components from)))
4426                     (concat "\n ("
4427                             (or (car pair) (cadr pair))
4428                             "'s message of \""
4429                             (if (or (not date) (string= date ""))
4430                                 "(unknown date)" date)
4431                             "\")"))))))))
4432
4433 (defun message-make-distribution ()
4434   "Make a Distribution header."
4435   (let ((orig-distribution (message-fetch-reply-field "distribution")))
4436     (cond ((message-functionp message-distribution-function)
4437            (funcall message-distribution-function))
4438           (t orig-distribution))))
4439
4440 (defun message-make-expires ()
4441   "Return an Expires header based on `message-expires'."
4442   (let ((current (current-time))
4443         (future (* 1.0 message-expires 60 60 24)))
4444     ;; Add the future to current.
4445     (setcar current (+ (car current) (round (/ future (expt 2 16)))))
4446     (setcar (cdr current) (+ (nth 1 current) (% (round future) (expt 2 16))))
4447     (message-make-date current)))
4448
4449 (defun message-make-path ()
4450   "Return uucp path."
4451   (let ((login-name (user-login-name)))
4452     (cond ((null message-user-path)
4453            (concat (system-name) "!" login-name))
4454           ((stringp message-user-path)
4455            ;; Support GENERICPATH.  Suggested by vixie@decwrl.dec.com.
4456            (concat message-user-path "!" login-name))
4457           (t login-name))))
4458
4459 (defun message-make-from ()
4460   "Make a From header."
4461   (let* ((style message-from-style)
4462          (login (message-make-address))
4463          (fullname
4464           (or (and (boundp 'user-full-name)
4465                    user-full-name)
4466               (user-full-name))))
4467     (when (string= fullname "&")
4468       (setq fullname (user-login-name)))
4469     (save-excursion
4470       (message-set-work-buffer)
4471       (cond
4472        ((or (null style)
4473             (equal fullname ""))
4474         (insert login))
4475        ((or (eq style 'angles)
4476             (and (not (eq style 'parens))
4477                  ;; Use angles if no quoting is needed, or if parens would
4478                  ;; need quoting too.
4479                  (or (not (string-match "[^- !#-'*+/-9=?A-Z^-~]" fullname))
4480                      (let ((tmp (concat fullname nil)))
4481                        (while (string-match "([^()]*)" tmp)
4482                          (aset tmp (match-beginning 0) ?-)
4483                          (aset tmp (1- (match-end 0)) ?-))
4484                        (string-match "[\\()]" tmp)))))
4485         (insert fullname)
4486         (insert " <" login ">"))
4487        (t                               ; 'parens or default
4488         (insert login " (")
4489         (let ((fullname-start (point)))
4490           (insert fullname)
4491           (goto-char fullname-start)
4492           ;; RFC 822 says \ and nonmatching parentheses
4493           ;; must be escaped in comments.
4494           ;; Escape every instance of ()\ ...
4495           (while (re-search-forward "[()\\]" nil 1)
4496             (replace-match "\\\\\\&" t))
4497           ;; ... then undo escaping of matching parentheses,
4498           ;; including matching nested parentheses.
4499           (goto-char fullname-start)
4500           (while (re-search-forward
4501                   "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
4502                   nil 1)
4503             (replace-match "\\1(\\3)" t)
4504             (goto-char fullname-start)))
4505         (insert ")")))
4506       (buffer-string))))
4507
4508 (defun message-make-sender ()
4509   "Return the \"real\" user address.
4510 This function tries to ignore all user modifications, and
4511 give as trustworthy answer as possible."
4512   (concat (user-login-name) "@" (system-name)))
4513
4514 (defun message-make-address ()
4515   "Make the address of the user."
4516   (or (message-user-mail-address)
4517       (concat (user-login-name) "@" (message-make-domain))))
4518
4519 (defun message-user-mail-address ()
4520   "Return the pertinent part of `user-mail-address'."
4521   (when user-mail-address
4522     (if (string-match " " user-mail-address)
4523         (nth 1 (std11-extract-address-components user-mail-address))
4524       user-mail-address)))
4525
4526 (defun message-make-fqdn ()
4527   "Return user's fully qualified domain name."
4528   (let ((system-name (system-name))
4529         (user-mail (message-user-mail-address)))
4530     (cond
4531      ((and (string-match "[^.]\\.[^.]" system-name)
4532            (not (string-match message-bogus-system-names system-name)))
4533       ;; `system-name' returned the right result.
4534       system-name)
4535      ;; Try `mail-host-address'.
4536      ((and (boundp 'mail-host-address)
4537            (stringp mail-host-address)
4538            (string-match "\\." mail-host-address))
4539       mail-host-address)
4540      ;; We try `user-mail-address' as a backup.
4541      ((and user-mail
4542            (string-match "\\." user-mail)
4543            (string-match "@\\(.*\\)\\'" user-mail))
4544       (match-string 1 user-mail))
4545      ;; Default to this bogus thing.
4546      (t
4547       (concat system-name ".i-did-not-set--mail-host-address--so-tickle-me")))))
4548
4549 (defun message-make-host-name ()
4550   "Return the name of the host."
4551   (let ((fqdn (message-make-fqdn)))
4552     (string-match "^[^.]+\\." fqdn)
4553     (substring fqdn 0 (1- (match-end 0)))))
4554
4555 (defun message-make-domain ()
4556   "Return the domain name."
4557   (or mail-host-address
4558       (message-make-fqdn)))
4559
4560 (defun message-make-mft ()
4561   "Return the Mail-Followup-To header."
4562   (let* ((case-fold-search t)
4563          (msg-recipients (message-options-get 'message-recipients))
4564          (recipients
4565           (mapcar 'mail-strip-quoted-names
4566                   (message-tokenize-header msg-recipients)))
4567          (file-regexps
4568           (if message-subscribed-address-file
4569               (let (begin end item re)
4570                 (save-excursion
4571                   (with-temp-buffer
4572                     (insert-file-contents message-subscribed-address-file)
4573                     (while (not (eobp))
4574                       (setq begin (point))
4575                       (forward-line 1)
4576                       (setq end (point))
4577                       (if (bolp) (setq end (1- end)))
4578                       (setq item (regexp-quote (buffer-substring begin end)))
4579                       (if re (setq re (concat re "\\|" item))
4580                         (setq re (concat "\\`\\(" item))))
4581                     (and re (list (concat re "\\)\\'"))))))))
4582          (mft-regexps (apply 'append message-subscribed-regexps
4583                              (mapcar 'regexp-quote
4584                                      message-subscribed-addresses)
4585                              file-regexps
4586                              (mapcar 'funcall
4587                                      message-subscribed-address-functions))))
4588     (save-match-data
4589       (when (eval
4590              (apply 'append '(or)
4591                     (mapcar
4592                      #'(lambda (regexp)
4593                          (mapcar
4594                           #'(lambda (recipient)
4595                               `(string-match ,regexp ,recipient))
4596                           recipients))
4597                      mft-regexps)))
4598         msg-recipients))))
4599
4600 ;; Dummy to avoid byte-compile warning.
4601 (defvar mule-version)
4602 (defvar emacs-beta-version)
4603 (defvar xemacs-codename)
4604 (defvar gnus-inviolable-extended-version)
4605
4606 (defun message-make-user-agent ()
4607   "Return user-agent info if the value `message-user-agent' is non-nil. If the
4608 \"User-Agent\" field has already exist, it's value will be added in the return
4609 string."
4610   (when message-user-agent
4611     (save-excursion
4612       (goto-char (point-min))
4613       (let ((case-fold-search t)
4614             user-agent start p end)
4615         (if (re-search-forward "^User-Agent:[\t ]*" nil t)
4616             (progn
4617               (setq start (match-beginning 0)
4618                     p (match-end 0)
4619                     end (std11-field-end)
4620                     user-agent (buffer-substring-no-properties p end))
4621               (delete-region start (1+ end))
4622               (concat message-user-agent " " user-agent))
4623           message-user-agent)))))
4624
4625 (defun message-generate-headers (headers)
4626   "Prepare article HEADERS.
4627 Headers already prepared in the buffer are not modified."
4628   (save-restriction
4629     (message-narrow-to-headers)
4630     (let* ((Date (message-make-date))
4631            (Message-ID (message-make-message-id))
4632            (Organization (message-make-organization))
4633            (From (message-make-from))
4634            (Path (message-make-path))
4635            (Subject nil)
4636            (Newsgroups nil)
4637            (In-Reply-To (message-make-in-reply-to))
4638            (To nil)
4639            (Distribution (message-make-distribution))
4640            (Lines (message-make-lines))
4641            (User-Agent (message-make-user-agent))
4642            (Expires (message-make-expires))
4643            (case-fold-search t)
4644            header value elem)
4645       ;; First we remove any old generated headers.
4646       (let ((headers message-deletable-headers))
4647         (unless (buffer-modified-p)
4648           (setq headers (delq 'Message-ID (copy-sequence headers))))
4649         (while headers
4650           (goto-char (point-min))
4651           (and (re-search-forward
4652                 (concat "^" (symbol-name (car headers)) ": *") nil t)
4653                (get-text-property (1+ (match-beginning 0)) 'message-deletable)
4654                (message-delete-line))
4655           (pop headers)))
4656       ;; Go through all the required headers and see if they are in the
4657       ;; articles already.  If they are not, or are empty, they are
4658       ;; inserted automatically - except for Subject, Newsgroups and
4659       ;; Distribution.
4660       (while headers
4661         (goto-char (point-min))
4662         (setq elem (pop headers))
4663         (if (consp elem)
4664             (if (eq (car elem) 'optional)
4665                 (setq header (cdr elem))
4666               (setq header (car elem)))
4667           (setq header elem))
4668         (when (or (not (re-search-forward
4669                         (concat "^"
4670                                 (regexp-quote
4671                                  (downcase
4672                                   (if (stringp header)
4673                                       header
4674                                     (symbol-name header))))
4675                                 ":")
4676                         nil t))
4677                   (progn
4678                     ;; The header was found.  We insert a space after the
4679                     ;; colon, if there is none.
4680                     (if (/= (char-after) ? ) (insert " ") (forward-char 1))
4681                     ;; Find out whether the header is empty...
4682                     (looking-at "[ \t]*\n[^ \t]")))
4683           ;; So we find out what value we should insert.
4684           (setq value
4685                 (cond
4686                  ((and (consp elem) (eq (car elem) 'optional))
4687                   ;; This is an optional header.  If the cdr of this
4688                   ;; is something that is nil, then we do not insert
4689                   ;; this header.
4690                   (setq header (cdr elem))
4691                   (or (and (fboundp (cdr elem)) (funcall (cdr elem)))
4692                       (and (boundp (cdr elem)) (symbol-value (cdr elem)))))
4693                  ((consp elem)
4694                   ;; The element is a cons.  Either the cdr is a
4695                   ;; string to be inserted verbatim, or it is a
4696                   ;; function, and we insert the value returned from
4697                   ;; this function.
4698                   (or (and (stringp (cdr elem)) (cdr elem))
4699                       (and (fboundp (cdr elem)) (funcall (cdr elem)))))
4700                  ((and (boundp header) (symbol-value header))
4701                   ;; The element is a symbol.  We insert the value
4702                   ;; of this symbol, if any.
4703                   (symbol-value header))
4704                  ((not (message-check-element header))
4705                   ;; We couldn't generate a value for this header,
4706                   ;; so we just ask the user.
4707                   (read-from-minibuffer
4708                    (format "Empty header for %s; enter value: " header)))))
4709           ;; Finally insert the header.
4710           (when (and value
4711                      (not (equal value "")))
4712             (save-excursion
4713               (if (bolp)
4714                   (progn
4715                     ;; This header didn't exist, so we insert it.
4716                     (goto-char (point-max))
4717                     (insert (if (stringp header) header (symbol-name header))
4718                             ": " value)
4719                     ;; We check whether the value was ended by a
4720                     ;; newline.  If now, we insert one.
4721                     (unless (bolp)
4722                       (insert "\n"))
4723                     (forward-line -1))
4724                 ;; The value of this header was empty, so we clear
4725                 ;; totally and insert the new value.
4726                 (delete-region (point) (gnus-point-at-eol))
4727                 (insert value)
4728                 (when (bolp)
4729                   (delete-char -1)))
4730               ;; Add the deletable property to the headers that require it.
4731               (and (memq header message-deletable-headers)
4732                    (progn (beginning-of-line) (looking-at "[^:]+: "))
4733                    (add-text-properties
4734                     (point) (match-end 0)
4735                     '(message-deletable t face italic) (current-buffer)))))))
4736       ;; Insert new Sender if the From is strange.
4737       (let ((from (message-fetch-field "from"))
4738             (sender (message-fetch-field "sender"))
4739             (secure-sender (message-make-sender)))
4740         (when (and from
4741                    (not (message-check-element 'sender))
4742                    (not (string=
4743                          (downcase
4744                           (cadr (std11-extract-address-components from)))
4745                          (downcase secure-sender)))
4746                    (or (null sender)
4747                        (not
4748                         (string=
4749                          (downcase
4750                           (cadr (std11-extract-address-components sender)))
4751                          (downcase secure-sender)))))
4752           (goto-char (point-min))
4753           ;; Rename any old Sender headers to Original-Sender.
4754           (when (re-search-forward "^\\(Original-\\)*Sender:" nil t)
4755             (beginning-of-line)
4756             (insert "Original-")
4757             (beginning-of-line))
4758           (when (or (message-news-p)
4759                     (string-match "@.+\\.." secure-sender))
4760             (insert "Sender: " secure-sender "\n")))))))
4761
4762 (defun message-insert-courtesy-copy ()
4763   "Insert a courtesy message in mail copies of combined messages."
4764   (let (newsgroups)
4765     (save-excursion
4766       (save-restriction
4767         (message-narrow-to-headers)
4768         (when (setq newsgroups (message-fetch-field "newsgroups"))
4769           (goto-char (point-max))
4770           (insert "Posted-To: " newsgroups "\n")))
4771       (forward-line 1)
4772       (when message-courtesy-message
4773         (cond
4774          ((string-match "%s" message-courtesy-message)
4775           (insert (format message-courtesy-message newsgroups)))
4776          (t
4777           (insert message-courtesy-message)))))))
4778
4779 ;;;
4780 ;;; Setting up a message buffer
4781 ;;;
4782
4783 (defun message-fill-address (header value)
4784   (save-restriction
4785     (narrow-to-region (point) (point))
4786     (insert (capitalize (symbol-name header))
4787             ": "
4788             (if (consp value) (car value) value)
4789             "\n")
4790     (narrow-to-region (point-min) (1- (point-max)))
4791     (let (quoted last)
4792       (goto-char (point-min))
4793       (while (not (eobp))
4794         (skip-chars-forward "^,\"" (point-max))
4795         (if (or (eq (char-after) ?,)
4796                 (eobp))
4797             (when (not quoted)
4798               (if (and (> (current-column) 78)
4799                        last)
4800                   (save-excursion
4801                     (goto-char last)
4802                     (looking-at "[ \t]*")
4803                     (replace-match "\n " t t)))
4804               (setq last (1+ (point))))
4805           (setq quoted (not quoted)))
4806         (unless (eobp)
4807           (forward-char 1))))
4808     (goto-char (point-max))
4809     (widen)
4810     (forward-line 1)))
4811
4812 (defun message-fill-references (header value)
4813   (insert (capitalize (symbol-name header))
4814           ": "
4815           (std11-fill-msg-id-list-string
4816            (if (consp value) (car value) value))
4817           "\n"))
4818
4819 (defun message-fill-header (header value)
4820   (let ((begin (point))
4821         (fill-column 78)
4822         (fill-prefix " "))
4823     (insert (capitalize (symbol-name header))
4824             ": "
4825             (if (consp value) (car value) value)
4826             "\n")
4827     (save-restriction
4828       (narrow-to-region begin (point))
4829       (fill-region-as-paragraph begin (point))
4830       ;; Tapdance around looong Message-IDs.
4831       (forward-line -1)
4832       (when (looking-at "[ \t]*$")
4833         (message-delete-line))
4834       (goto-char begin)
4835       (re-search-forward ":" nil t)
4836       (when (looking-at "\n[ \t]+")
4837         (replace-match " " t t))
4838       (goto-char (point-max)))))
4839
4840 (defun message-shorten-1 (list cut surplus)
4841   "Cut SURPLUS elements out of LIST, beginning with CUTth one."
4842   (setcdr (nthcdr (- cut 2) list)
4843           (nthcdr (+ (- cut 2) surplus 1) list)))
4844
4845 (defun message-shorten-references (header references)
4846   "Trim REFERENCES to be 21 Message-ID long or less, and fold them.
4847 If folding is disallowed, also check that the REFERENCES are less
4848 than 988 characters long, and if they are not, trim them until they are."
4849   (let ((maxcount 21)
4850         (count 0)
4851         (cut 2)
4852         refs)
4853     (with-temp-buffer
4854       (insert references)
4855       (goto-char (point-min))
4856       ;; Cons a list of valid references.
4857       (while (re-search-forward "<[^>]+>" nil t)
4858         (push (match-string 0) refs))
4859       (setq refs (nreverse refs)
4860             count (length refs)))
4861
4862     ;; If the list has more than MAXCOUNT elements, trim it by
4863     ;; removing the CUTth element and the required number of
4864     ;; elements that follow.
4865     (when (> count maxcount)
4866       (let ((surplus (- count maxcount)))
4867         (message-shorten-1 refs cut surplus)
4868         (decf count surplus)))
4869
4870     ;; If folding is disallowed, make sure the total length (including
4871     ;; the spaces between) will be less than MAXSIZE characters.
4872     ;;
4873     ;; Only disallow folding for News messages. At this point the headers
4874     ;; have not been generated, thus we use message-this-is-news directly.
4875     (when (and message-this-is-news message-cater-to-broken-inn)
4876       (let ((maxsize 988)
4877             (totalsize (+ (apply #'+ (mapcar #'length refs))
4878                           (1- count)))
4879             (surplus 0)
4880             (ptr (nthcdr (1- cut) refs)))
4881         ;; Decide how many elements to cut off...
4882         (while (> totalsize maxsize)
4883           (decf totalsize (1+ (length (car ptr))))
4884           (incf surplus)
4885           (setq ptr (cdr ptr)))
4886         ;; ...and do it.
4887         (when (> surplus 0)
4888           (message-shorten-1 refs cut surplus))))
4889
4890     ;; Finally, collect the references back into a string and insert
4891     ;; it into the buffer.
4892     (let ((refstring (mapconcat #'identity refs " ")))
4893       (if (and message-this-is-news message-cater-to-broken-inn)
4894           (insert (capitalize (symbol-name header)) ": "
4895                   refstring "\n")
4896         (message-fill-header header refstring)))))
4897
4898 (defun message-position-point ()
4899   "Move point to where the user probably wants to find it."
4900   (message-narrow-to-headers)
4901   (cond
4902    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
4903     (search-backward ":" )
4904     (widen)
4905     (forward-char 1)
4906     (if (eq (char-after) ? )
4907         (forward-char 1)
4908       (insert " ")))
4909    (t
4910     (goto-char (point-max))
4911     (widen)
4912     (forward-line 1)
4913     (unless (looking-at "$")
4914       (forward-line 2)))
4915    (sit-for 0)))
4916
4917 (defun message-beginning-of-line (&optional n)
4918   "Move point to beginning of header value or to beginning of line."
4919   (interactive "p")
4920   (if (message-point-in-header-p)
4921       (let* ((here (point))
4922              (bol (progn (beginning-of-line n) (point)))
4923              (eol (gnus-point-at-eol))
4924              (eoh (re-search-forward ": *" eol t)))
4925         (if (or (not eoh) (equal here eoh))
4926             (goto-char bol)
4927           (goto-char eoh)))
4928     (beginning-of-line n)))
4929
4930 (defun message-buffer-name (type &optional to group)
4931   "Return a new (unique) buffer name based on TYPE and TO."
4932   (cond
4933    ;; Generate a new buffer name The Message Way.
4934    ((eq message-generate-new-buffers 'unique)
4935     (generate-new-buffer-name
4936      (concat "*" type
4937              (if to
4938                  (concat " to "
4939                          (or (car (std11-extract-address-components to))
4940                              to) "")
4941                "")
4942              (if (and group (not (string= group ""))) (concat " on " group) "")
4943              "*")))
4944    ;; Check whether `message-generate-new-buffers' is a function,
4945    ;; and if so, call it.
4946    ((message-functionp message-generate-new-buffers)
4947     (funcall message-generate-new-buffers type to group))
4948    ((eq message-generate-new-buffers 'unsent)
4949     (generate-new-buffer-name
4950      (concat "*unsent " type
4951              (if to
4952                  (concat " to "
4953                          (or (car (mail-extract-address-components to))
4954                              to) "")
4955                "")
4956              (if (and group (not (string= group ""))) (concat " on " group) "")
4957              "*")))
4958    ;; Use standard name.
4959    (t
4960     (format "*%s message*" type))))
4961
4962 (defmacro message-pop-to-buffer-1 (buffer)
4963   `(if pop-up-frames
4964        (let (special-display-buffer-names
4965              special-display-regexps
4966              same-window-buffer-names
4967              same-window-regexps)
4968          (pop-to-buffer ,buffer))
4969      (pop-to-buffer ,buffer)))
4970
4971 (defun message-pop-to-buffer (name)
4972   "Pop to buffer NAME, and warn if it already exists and is modified."
4973   (let ((buffer (get-buffer name))
4974         (pop-up-frames (and (or (static-if (featurep 'xemacs)
4975                                     (device-on-window-system-p)
4976                                   window-system)
4977                                 (>= emacs-major-version 20))
4978                             message-use-multi-frames)))
4979     (if (and buffer
4980              (buffer-name buffer))
4981         (progn
4982           (message-pop-to-buffer-1 buffer)
4983           (when (and (buffer-modified-p)
4984                      (not (y-or-n-p
4985                            "Message already being composed; erase? ")))
4986             (error "Message being composed")))
4987       (message-pop-to-buffer-1 name))
4988     (erase-buffer)
4989     (message-mode)
4990     (when pop-up-frames
4991       (set (make-local-variable 'message-original-frame) (selected-frame)))))
4992
4993 (defun message-do-send-housekeeping ()
4994   "Kill old message buffers."
4995   ;; We might have sent this buffer already.  Delete it from the
4996   ;; list of buffers.
4997   (setq message-buffer-list (delq (current-buffer) message-buffer-list))
4998   (while (and message-max-buffers
4999               message-buffer-list
5000               (>= (length message-buffer-list) message-max-buffers))
5001     ;; Kill the oldest buffer -- unless it has been changed.
5002     (let ((buffer (pop message-buffer-list)))
5003       (when (and (buffer-name buffer)
5004                  (not (buffer-modified-p buffer)))
5005         (kill-buffer buffer))))
5006   ;; Rename the buffer.
5007   (if message-send-rename-function
5008       (funcall message-send-rename-function)
5009     ;; Note: mail-abbrevs of XEmacs renames buffer name behind Gnus.
5010     (when (string-match
5011            "\\`\\*\\(sent \\|unsent \\)?\\(.+\\)\\*[^\\*]*\\|\\`mail to "
5012            (buffer-name))
5013       (let ((name (match-string 2 (buffer-name)))
5014             to group)
5015         (if (not (or (null name)
5016                      (string-equal name "mail")
5017                      (string-equal name "posting")))
5018             (setq name (concat "*sent " name "*"))
5019           (message-narrow-to-headers)
5020           (setq to (message-fetch-field "to"))
5021           (setq group (message-fetch-field "newsgroups"))
5022           (widen)
5023           (setq name
5024                 (cond
5025                  (to (concat "*sent mail to "
5026                              (or (car (mail-extract-address-components to))
5027                                  to) "*"))
5028                  ((and group (not (string= group "")))
5029                   (concat "*sent posting on " group "*"))
5030                  (t "*sent mail*"))))
5031         (unless (string-equal name (buffer-name))
5032           (rename-buffer name t)))))
5033   ;; Push the current buffer onto the list.
5034   (when message-max-buffers
5035     (setq message-buffer-list
5036           (nconc message-buffer-list (list (current-buffer))))))
5037
5038 (defun message-mail-user-agent ()
5039   (let ((mua (cond
5040               ((not message-mail-user-agent) nil)
5041               ((eq message-mail-user-agent t) mail-user-agent)
5042               (t message-mail-user-agent))))
5043     (if (memq mua '(message-user-agent gnus-user-agent))
5044         nil
5045       mua)))
5046
5047 (defun message-setup (headers &optional replybuffer actions switch-function)
5048   (let ((mua (message-mail-user-agent))
5049         subject to field yank-action)
5050     (if (not (and message-this-is-mail mua))
5051         (message-setup-1 headers replybuffer actions)
5052       (if replybuffer
5053           (setq yank-action (list 'insert-buffer replybuffer)))
5054       (setq headers (copy-sequence headers))
5055       (setq field (assq 'Subject headers))
5056       (when field
5057         (setq subject (cdr field))
5058         (setq headers (delq field headers)))
5059       (setq field (assq 'To headers))
5060       (when field
5061         (setq to (cdr field))
5062         (setq headers (delq field headers)))
5063       (let ((mail-user-agent mua))
5064         (compose-mail to subject
5065                       (mapcar (lambda (item)
5066                                 (cons
5067                                  (format "%s" (car item))
5068                                  (cdr item)))
5069                               headers)
5070                       nil switch-function yank-action actions)))))
5071
5072 (defun message-setup-1 (headers &optional replybuffer actions)
5073   (dolist (action actions)
5074     (condition-case nil
5075         (add-to-list 'message-send-actions
5076                      `(apply ',(car action) ',(cdr action)))))
5077   (setq message-reply-buffer
5078         (or (message-get-parameter 'reply-buffer)
5079             replybuffer))
5080   (goto-char (point-min))
5081   ;; Insert all the headers.
5082   (mail-header-format
5083    (let ((h headers)
5084          (alist message-header-format-alist))
5085      (while h
5086        (unless (assq (caar h) message-header-format-alist)
5087          (push (list (caar h)) alist))
5088        (pop h))
5089      alist)
5090    headers)
5091   (delete-region (point) (progn (forward-line -1) (point)))
5092   (when message-default-headers
5093     (insert message-default-headers)
5094     (or (bolp) (insert ?\n)))
5095   (put-text-property
5096    (point)
5097    (progn
5098      (insert mail-header-separator "\n")
5099      (1- (point)))
5100    'read-only nil)
5101   (forward-line -1)
5102   (when (message-news-p)
5103     (when message-default-news-headers
5104       (insert message-default-news-headers)
5105       (or (bolp) (insert ?\n)))
5106     (when message-generate-headers-first
5107       (message-generate-headers
5108        (delq 'Lines
5109              (delq 'Subject
5110                    (copy-sequence message-required-news-headers))))))
5111   (when (message-mail-p)
5112     (when message-default-mail-headers
5113       (insert message-default-mail-headers)
5114       (or (bolp) (insert ?\n)))
5115     (when message-generate-headers-first
5116       (message-generate-headers
5117        (delq 'Lines
5118              (delq 'Subject
5119                    (copy-sequence message-required-mail-headers))))))
5120   (run-hooks 'message-signature-setup-hook)
5121   (message-insert-signature)
5122   (save-restriction
5123     (message-narrow-to-headers)
5124     (if message-alternative-emails
5125         (message-use-alternative-email-as-from))
5126     (run-hooks 'message-header-setup-hook))
5127   (set-buffer-modified-p nil)
5128   (setq buffer-undo-list nil)
5129   (run-hooks 'message-setup-hook)
5130   (message-position-point)
5131   (undo-boundary))
5132
5133 (defun message-set-auto-save-file-name ()
5134   "Associate the message buffer with a file in the drafts directory."
5135   (when message-auto-save-directory
5136     (unless (file-directory-p
5137              (directory-file-name message-auto-save-directory))
5138       (gnus-make-directory message-auto-save-directory))
5139     (if (gnus-alive-p)
5140         (setq message-draft-article
5141               (nndraft-request-associate-buffer "drafts"))
5142       (setq buffer-file-name (expand-file-name
5143                               (if (memq system-type
5144                                         '(ms-dos ms-windows windows-nt
5145                                                  cygwin32 win32 w32
5146                                                  mswindows))
5147                                   "message"
5148                                 "*message*")
5149                               message-auto-save-directory))
5150       (setq buffer-auto-save-file-name (make-auto-save-file-name)))
5151     (clear-visited-file-modtime)
5152     (static-if (boundp 'MULE)
5153         (set-file-coding-system message-draft-coding-system)
5154       (setq buffer-file-coding-system message-draft-coding-system))))
5155
5156 (defun message-disassociate-draft ()
5157   "Disassociate the message buffer from the drafts directory."
5158   (when message-draft-article
5159     (nndraft-request-expire-articles
5160      (list message-draft-article) "drafts" nil t)))
5161
5162 (defun message-insert-headers ()
5163   "Generate the headers for the article."
5164   (interactive)
5165   (save-excursion
5166     (save-restriction
5167       (message-narrow-to-headers)
5168       (when (message-news-p)
5169         (message-generate-headers
5170          (delq 'Lines
5171                (delq 'Subject
5172                      (copy-sequence message-required-news-headers)))))
5173       (when (message-mail-p)
5174         (message-generate-headers
5175          (delq 'Lines
5176                (delq 'Subject
5177                      (copy-sequence message-required-mail-headers))))))))
5178
5179 \f
5180
5181 ;;;
5182 ;;; Commands for interfacing with message
5183 ;;;
5184
5185 ;;;###autoload
5186 (defun message-mail (&optional to subject
5187                                other-headers continue switch-function
5188                                yank-action send-actions)
5189   "Start editing a mail message to be sent.
5190 OTHER-HEADERS is an alist of header/value pairs."
5191   (interactive)
5192   (let ((message-this-is-mail t) replybuffer)
5193     (unless (message-mail-user-agent)
5194       (message-pop-to-buffer (message-buffer-name "mail" to)))
5195     ;; FIXME: message-mail should do something if YANK-ACTION is not
5196     ;; insert-buffer.
5197     (and (consp yank-action) (eq (car yank-action) 'insert-buffer)
5198          (setq replybuffer (nth 1 yank-action)))
5199     (message-setup
5200      (nconc
5201       `((To . ,(or to "")) (Subject . ,(or subject "")))
5202       (when other-headers other-headers))
5203      replybuffer send-actions)
5204     ;; FIXME: Should return nil if failure.
5205     t))
5206
5207 ;;;###autoload
5208 (defun message-news (&optional newsgroups subject)
5209   "Start editing a news article to be sent."
5210   (interactive)
5211   (let ((message-this-is-news t))
5212     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups))
5213     (message-setup `((Newsgroups . ,(or newsgroups ""))
5214                      (Subject . ,(or subject ""))))))
5215
5216 (defun message-get-reply-headers (wide &optional to-address)
5217   (let (follow-to mct never-mct to cc author mft recipients)
5218     ;; Find all relevant headers we need.
5219     (let ((mrt (when message-use-mail-reply-to
5220                  (message-fetch-field "mail-reply-to")))
5221           (reply-to (message-fetch-field "reply-to")))
5222       (setq to (message-fetch-field "to")
5223             cc (message-fetch-field "cc")
5224             mct (when message-use-mail-copies-to
5225                   (message-fetch-field "mail-copies-to"))
5226             author (or mrt
5227                        reply-to
5228                        (message-fetch-field "from")
5229                        "")
5230             mft (when (and (not (or to-address mrt reply-to))
5231                            message-use-mail-followup-to)
5232                   (message-fetch-field "mail-followup-to"))))
5233
5234     (save-match-data
5235       ;; Handle special values of Mail-Copies-To.
5236       (when mct
5237         (cond ((or (equal (downcase mct) "never")
5238                    (equal (downcase mct) "nobody"))
5239                (when (or (not (eq message-use-mail-copies-to 'ask))
5240                          (message-y-or-n-p
5241                           (concat "Obey Mail-Copies-To: never? ") t "\
5242 You should normally obey the Mail-Copies-To: header.
5243
5244         `Mail-Copies-To: " mct "'
5245 directs you not to send your response to the author."))
5246                  (setq never-mct t))
5247                (setq mct nil))
5248               ((or (equal (downcase mct) "always")
5249                    (equal (downcase mct) "poster"))
5250                (if (or (not (eq message-use-mail-copies-to 'ask))
5251                        (message-y-or-n-p
5252                         (concat "Obey Mail-Copies-To: always? ") t "\
5253 You should normally obey the Mail-Copies-To: header.
5254
5255         `Mail-Copies-To: " mct "'
5256 sends a copy of your response to the author."))
5257                    (setq mct author)
5258                  (setq mct nil)))
5259               ((and (eq message-use-mail-copies-to 'ask)
5260                     (not (message-y-or-n-p
5261                           (concat "Obey Mail-Copies-To: " mct " ? ") t "\
5262 You should normally obey the Mail-Copies-To: header.
5263
5264         `Mail-Copies-To: " mct "'
5265 sends a copy of your response to " (if (string-match "," mct)
5266                                        "the specified addresses"
5267                                      "that address") ".")))
5268                (setq mct nil))))
5269
5270       ;; Build (textual) list of new recipient addresses.
5271       (cond
5272        ((not wide)
5273         (setq recipients (concat ", " author)))
5274        ((and mft
5275              (string-match "[^ \t,]" mft)
5276              (or (not (eq message-use-mail-followup-to 'ask))
5277                  (message-y-or-n-p "Obey Mail-Followup-To? " t "\
5278 You should normally obey the Mail-Followup-To: header.  In this
5279 article, it has the value of
5280
5281 " mft "
5282
5283 which directs your response to " (if (string-match "," mft)
5284                                      "the specified addresses"
5285                                    "that address only") ".
5286
5287 Most commonly, Mail-Followup-To is used by a mailing list poster to
5288 express that responses should be sent to just the list, and not the
5289 poster as well.
5290
5291 If a message is posted to several mailing lists, Mail-Followup-To may
5292 also be used to direct the following discussion to one list only,
5293 because discussions that are spread over several lists tend to be
5294 fragmented and very difficult to follow.
5295
5296 Also, some source/announcement lists are not intended for discussion;
5297 responses here are directed to other addresses.")))
5298         (setq recipients (concat ", " mft)))
5299        (to-address
5300         (setq recipients (concat ", " to-address))
5301         ;; If the author explicitly asked for a copy, we don't deny it to them.
5302         (if mct (setq recipients (concat recipients ", " mct))))
5303        (t
5304         (setq recipients (if never-mct "" (concat ", " author)))
5305         (if to  (setq recipients (concat recipients ", " to)))
5306         (if cc  (setq recipients (concat recipients ", " cc)))
5307         (if mct (setq recipients (concat recipients ", " mct)))))
5308       (if (>= (length recipients) 2)
5309           ;; Strip the leading ", ".
5310           (setq recipients (substring recipients 2)))
5311       ;; Squeeze whitespace.
5312       (while (string-match "[ \t][ \t]+" recipients)
5313         (setq recipients (replace-match " " t t recipients)))
5314       ;; Remove addresses that match `rmail-dont-reply-to-names'.
5315       (let ((rmail-dont-reply-to-names message-dont-reply-to-names))
5316         (setq recipients (rmail-dont-reply-to recipients)))
5317       ;; Perhaps "Mail-Copies-To: never" removed the only address?
5318       (if (string-equal recipients "")
5319           (setq recipients author))
5320       ;; Convert string to a list of (("foo@bar" . "Name <Foo@BAR>") ...).
5321       (setq recipients
5322             (mapcar
5323              (lambda (addr)
5324                (cons (downcase (mail-strip-quoted-names addr)) addr))
5325              (message-tokenize-header recipients)))
5326       ;; Remove first duplicates.  (Why not all duplicates?  Is this a bug?)
5327       (let ((s recipients))
5328         (while s
5329           (setq recipients (delq (assoc (car (pop s)) s) recipients))))
5330
5331       ;; Remove hierarchical lists that are contained within each other,
5332       ;; if message-hierarchical-addresses is defined.
5333       (when message-hierarchical-addresses
5334         (let ((plain-addrs (mapcar 'car recipients))
5335               subaddrs recip)
5336           (while plain-addrs
5337             (setq subaddrs (assoc (car plain-addrs)
5338                                   message-hierarchical-addresses)
5339                   plain-addrs (cdr plain-addrs))
5340             (when subaddrs
5341               (setq subaddrs (cdr subaddrs))
5342               (while subaddrs
5343                 (setq recip (assoc (car subaddrs) recipients)
5344                       subaddrs (cdr subaddrs))
5345                 (if recip
5346                     (setq recipients (delq recip recipients))))))))
5347
5348       ;; Build the header alist.  Allow the user to be asked whether
5349       ;; or not to reply to all recipients in a wide reply.
5350       (setq follow-to (list (cons 'To (cdr (pop recipients)))))
5351       (when (and recipients
5352                  (or (not message-wide-reply-confirm-recipients)
5353                      (y-or-n-p "Reply to all recipients? ")))
5354         (setq recipients (mapconcat
5355                           (lambda (addr) (cdr addr)) recipients ", "))
5356         (if (string-match "^ +" recipients)
5357             (setq recipients (substring recipients (match-end 0))))
5358         (push (cons 'Cc recipients) follow-to)))
5359     follow-to))
5360
5361 ;;;###autoload
5362 (defun message-reply (&optional to-address wide)
5363   "Start editing a reply to the article in the current buffer."
5364   (interactive)
5365   (require 'gnus-sum)                   ; for gnus-list-identifiers
5366   (let ((cur (current-buffer))
5367         from subject date
5368         references message-id follow-to
5369         (inhibit-point-motion-hooks t)
5370         (message-this-is-mail t)
5371         gnus-warning in-reply-to)
5372     (save-restriction
5373       (message-narrow-to-head-1)
5374       ;; Allow customizations to have their say.
5375       (if (not wide)
5376           ;; This is a regular reply.
5377           (when (message-functionp message-reply-to-function)
5378             (save-excursion
5379               (setq follow-to (funcall message-reply-to-function))))
5380         ;; This is a followup.
5381         (when (message-functionp message-wide-reply-to-function)
5382           (save-excursion
5383             (setq follow-to
5384                   (funcall message-wide-reply-to-function)))))
5385       (setq message-id (message-fetch-field "message-id" t)
5386             references (message-fetch-field "references")
5387             date (message-fetch-field "date")
5388             from (message-fetch-field "from")
5389             subject (or (message-fetch-field "subject") "none"))
5390       (when gnus-list-identifiers
5391         (setq subject (message-strip-list-identifiers subject)))
5392       (setq subject (message-make-followup-subject subject))
5393
5394       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
5395                  (string-match "<[^>]+>" gnus-warning))
5396         (setq message-id (match-string 0 gnus-warning)))
5397
5398       (unless follow-to
5399         (setq follow-to (message-get-reply-headers wide to-address)))
5400
5401       ;; Get the references from "In-Reply-To" field if there were
5402       ;; no references and "In-Reply-To" field looks promising.
5403       (unless references
5404         (when (and (setq in-reply-to (message-fetch-field "in-reply-to"))
5405                    (string-match "<[^>]+>" in-reply-to))
5406           (setq references (match-string 0 in-reply-to)))))
5407
5408     (unless (message-mail-user-agent)
5409       (message-pop-to-buffer
5410        (message-buffer-name
5411         (if wide "wide reply" "reply") from
5412         (if wide to-address nil))))
5413
5414     (setq message-reply-headers
5415           (make-full-mail-header-from-decoded-header
5416            0 subject from date message-id references 0 0 ""))
5417
5418     (message-setup
5419      `((Subject . ,subject)
5420        ,@follow-to
5421        ,@(if (or references message-id)
5422              `((References . ,(concat (or references "") (and references " ")
5423                                       (or message-id ""))))
5424            nil))
5425      cur)))
5426
5427 ;;;###autoload
5428 (defun message-wide-reply (&optional to-address)
5429   "Make a \"wide\" reply to the message in the current buffer."
5430   (interactive)
5431   (message-reply to-address t))
5432
5433 ;;;###autoload
5434 (defun message-followup (&optional to-newsgroups)
5435   "Follow up to the message in the current buffer.
5436 If TO-NEWSGROUPS, use that as the new Newsgroups line."
5437   (interactive)
5438   (require 'gnus-sum)                   ; for gnus-list-identifiers
5439   (let ((cur (current-buffer))
5440         from subject date reply-to mrt mct mft
5441         references message-id follow-to
5442         (inhibit-point-motion-hooks t)
5443         (message-this-is-news t)
5444         followup-to distribution newsgroups gnus-warning posted-to)
5445     (save-restriction
5446       (message-narrow-to-head)
5447       (when (message-functionp message-followup-to-function)
5448         (setq follow-to
5449               (funcall message-followup-to-function)))
5450       (setq from (message-fetch-field "from")
5451             date (message-fetch-field "date")
5452             subject (or (message-fetch-field "subject") "none")
5453             references (message-fetch-field "references")
5454             message-id (message-fetch-field "message-id" t)
5455             followup-to (message-fetch-field "followup-to")
5456             newsgroups (message-fetch-field "newsgroups")
5457             posted-to (message-fetch-field "posted-to")
5458             reply-to (message-fetch-field "reply-to")
5459             mrt (when message-use-mail-reply-to
5460                   (message-fetch-field "mail-reply-to"))
5461             distribution (message-fetch-field "distribution")
5462             mct (when message-use-mail-copies-to
5463                   (message-fetch-field "mail-copies-to"))
5464             mft (when message-use-mail-followup-to
5465                   (message-fetch-field "mail-followup-to")))
5466       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
5467                  (string-match "<[^>]+>" gnus-warning))
5468         (setq message-id (match-string 0 gnus-warning)))
5469       ;; Remove bogus distribution.
5470       (when (and (stringp distribution)
5471                  (let ((case-fold-search t))
5472                    (string-match "world" distribution)))
5473         (setq distribution nil))
5474       (if gnus-list-identifiers
5475           (setq subject (message-strip-list-identifiers subject)))
5476       (setq subject (message-make-followup-subject subject))
5477       (widen))
5478
5479     ;; Handle special values of Mail-Copies-To.
5480     (when mct
5481       (cond
5482        ((and (or (equal (downcase mct) "never")
5483                  (equal (downcase mct) "nobody")))
5484         (setq mct nil))
5485        ((and (or (equal (downcase mct) "always")
5486                  (equal (downcase mct) "poster")))
5487         (if (or (not (eq message-use-mail-copies-to 'ask))
5488                 (message-y-or-n-p
5489                  (concat "Obey Mail-Copies-To: always? ") t "\
5490 You should normally obey the Mail-Copies-To: header.
5491
5492         `Mail-Copies-To: " mct "'
5493 sends a copy of your response to the author."))
5494             (setq mct (or mrt reply-to from))
5495           (setq mct nil)))
5496        ((and (eq message-use-mail-copies-to 'ask)
5497              (not
5498               (message-y-or-n-p
5499                (concat "Obey Mail-Copies-To: " mct " ? ") t "\
5500 You should normally obey the Mail-Copies-To: header.
5501
5502         `Mail-Copies-To: " mct "'
5503 sends a copy of your response to " (if (string-match "," mct)
5504                                        "the specified addresses"
5505                                      "that address") ".")))
5506         (setq mct nil))))
5507
5508     (unless follow-to
5509       (cond
5510        (to-newsgroups (setq follow-to (list (cons 'Newsgroups to-newsgroups))))
5511        ;; Handle Followup-To.
5512        (followup-to
5513         (cond
5514          ((equal (downcase followup-to) "poster")
5515           (if (or (and followup-to (eq message-use-followup-to 'use))
5516                   (message-y-or-n-p "Obey Followup-To: poster? " t "\
5517 You should normally obey the Followup-To: header.
5518
5519         `Followup-To: poster'
5520 sends your response via e-mail instead of news.
5521
5522 A typical situation where `Followup-To: poster' is used is when the author
5523 does not read the newsgroup, so he wouldn't see any replies sent to it."))
5524               (setq message-this-is-news nil
5525                     distribution nil
5526                     follow-to (list (cons 'To (or mrt reply-to from ""))))
5527             (setq follow-to (list (cons 'Newsgroups newsgroups)))))
5528          (t
5529           (if (or (equal followup-to newsgroups)
5530                   (not (and followup-to (eq message-use-followup-to 'ask)))
5531                   (message-y-or-n-p
5532                    (concat "Obey Followup-To: " followup-to "? ") t "\
5533 You should normally obey the Followup-To: header.
5534
5535         `Followup-To: " followup-to "'
5536 directs your response to " (if (string-match "," followup-to)
5537                                "the specified newsgroups"
5538                              "that newsgroup only") ".
5539
5540 If a message is posted to several newsgroups, Followup-To is often
5541 used to direct the following discussion to one newsgroup only,
5542 because discussions that are spread over several newsgroup tend to
5543 be fragmented and very difficult to follow.
5544
5545 Also, some source/announcement newsgroups are not intended for discussion;
5546 responses here are directed to other newsgroups."))
5547               (setq follow-to (list (cons 'Newsgroups followup-to)))
5548             (setq follow-to (list (cons 'Newsgroups newsgroups)))))))
5549        ;; Handle Mail-Followup-To, followup via e-mail.
5550        ((and mft
5551              (or (not (eq message-use-mail-followup-to 'ask))
5552                  (message-y-or-n-p
5553                   (concat "Obey Mail-Followup-To: " mft "? ") t "\
5554 You should normally obey the Mail-Followup-To: header.
5555
5556         `Mail-Followup-To: " mft "'
5557 directs your response to " (if (string-match "," mft)
5558                                "the specified addresses"
5559                              "that address only") " instead of news.
5560
5561 A typical situation where Mail-Followup-To is used is when the author thinks
5562 that further discussion should take place only in "
5563                              (if (string-match "," mft)
5564                                  "the specified mailing lists"
5565                                "that mailing list") ".")))
5566         (setq message-this-is-news nil
5567               distribution nil
5568               follow-to (list (cons 'To mft))))
5569        (posted-to (setq follow-to (list (cons 'Newsgroups posted-to))))
5570        (t
5571         (setq follow-to (list (cons 'Newsgroups newsgroups))))))
5572
5573     (message-pop-to-buffer (message-buffer-name "followup" from newsgroups))
5574
5575     (message-setup
5576      `((Subject . ,subject)
5577        ,@follow-to
5578        ,@(and mct (list (cons 'Cc mct)))
5579        ,@(and distribution (list (cons 'Distribution distribution)))
5580        ,@(if (or references message-id)
5581              `((References . ,(concat (or references "") (and references " ")
5582                                       (or message-id ""))))))
5583      cur)
5584
5585     (setq message-reply-headers
5586           (make-full-mail-header-from-decoded-header
5587            0 subject from date message-id references 0 0 ""))))
5588
5589 ;;;###autoload
5590 (defun message-cancel-news (&optional arg)
5591   "Cancel an article you posted.
5592 If ARG, allow editing of the cancellation message."
5593   (interactive "P")
5594   (unless (message-news-p)
5595     (error "This is not a news article; canceling is impossible"))
5596   (let (from newsgroups message-id distribution buf sender)
5597     (save-excursion
5598       ;; Get header info from original article.
5599       (save-restriction
5600         (message-narrow-to-head-1)
5601         (setq from (message-fetch-field "from")
5602               sender (message-fetch-field "sender")
5603               newsgroups (message-fetch-field "newsgroups")
5604               message-id (message-fetch-field "message-id" t)
5605               distribution (message-fetch-field "distribution")))
5606       ;; Make sure that this article was written by the user.
5607       (unless (or
5608                ;; Canlock-logic as suggested by Per Abrahamsen
5609                ;; <abraham@dina.kvl.dk>
5610                ;;
5611                ;; IF article has cancel-lock THEN
5612                ;;   IF we can verify it THEN
5613                ;;     issue cancel
5614                ;;   ELSE
5615                ;;     error: cancellock: article is not yours
5616                ;; ELSE
5617                ;;   Use old rules, comparing sender...
5618                (if (message-fetch-field "Cancel-Lock")
5619                    (if (null (canlock-verify))
5620                        t
5621                      (error "Failed to verify Cancel-lock: This article is not yours"))
5622                  nil)
5623                (message-gnksa-enable-p 'cancel-messages)
5624                (and sender
5625                     (string-equal
5626                      (downcase sender)
5627                      (downcase (message-make-sender))))
5628                (string-equal
5629                 (downcase (cadr (std11-extract-address-components from)))
5630                 (downcase (cadr (std11-extract-address-components
5631                                  (message-make-from))))))
5632         (error "This article is not yours"))
5633       (when (yes-or-no-p "Do you really want to cancel this article? ")
5634         ;; Make control message.
5635         (if arg
5636             (message-news)
5637           (setq buf (set-buffer (get-buffer-create " *message cancel*"))))
5638         (erase-buffer)
5639         (insert "Newsgroups: " newsgroups "\n"
5640                 "From: " from "\n"
5641                 "Subject: cmsg cancel " message-id "\n"
5642                 "Control: cancel " message-id "\n"
5643                 (if distribution
5644                     (concat "Distribution: " distribution "\n")
5645                   "")
5646                 mail-header-separator "\n"
5647                 message-cancel-message)
5648         (run-hooks 'message-cancel-hook)
5649         (unless arg
5650           (message "Canceling your article...")
5651           (if (let ((message-syntax-checks
5652                      'dont-check-for-anything-just-trust-me)
5653                     (message-encoding-buffer (current-buffer))
5654                     (message-edit-buffer (current-buffer)))
5655                 (message-send-news))
5656               (message "Canceling your article...done"))
5657           (kill-buffer buf))))))
5658
5659 (defun message-supersede-setup-for-mime-edit ()
5660   (set (make-local-variable 'message-setup-hook) nil)
5661   (mime-edit-again))
5662
5663 ;;;###autoload
5664 (defun message-supersede ()
5665   "Start composing a message to supersede the current message.
5666 This is done simply by taking the old article and adding a Supersedes
5667 header line with the old Message-ID."
5668   (interactive)
5669   (let ((cur (current-buffer))
5670         (sender (message-fetch-field "sender"))
5671         (from (message-fetch-field "from")))
5672     ;; Check whether the user owns the article that is to be superseded.
5673     (unless (or
5674              ;; Canlock-logic as suggested by Per Abrahamsen
5675              ;; <abraham@dina.kvl.dk>
5676              ;;
5677              ;; IF article has cancel-lock THEN
5678              ;;   IF we can verify it THEN
5679              ;;     issue cancel
5680              ;;   ELSE
5681              ;;     error: cancellock: article is not yours
5682              ;; ELSE
5683              ;;   Use old rules, comparing sender...
5684              (if (message-fetch-field "Cancel-Lock")
5685                  (if (null (canlock-verify))
5686                      t
5687                    (error "Failed to verify Cancel-lock: This article is not yours"))
5688                nil)
5689              (message-gnksa-enable-p 'cancel-messages)
5690              (and sender
5691                   (string-equal
5692                    (downcase sender)
5693                    (downcase (message-make-sender))))
5694              (string-equal
5695               (downcase (cadr (std11-extract-address-components from)))
5696               (downcase (cadr (std11-extract-address-components
5697                                (message-make-from))))))
5698       (error "This article is not yours"))
5699     ;; Get a normal message buffer.
5700     (message-pop-to-buffer (message-buffer-name "supersede"))
5701     (insert-buffer-substring cur)
5702     (message-narrow-to-head-1)
5703     ;; Remove unwanted headers.
5704     (when message-ignored-supersedes-headers
5705       (message-remove-header message-ignored-supersedes-headers t))
5706     (goto-char (point-min))
5707     (if (not (re-search-forward "^Message-ID: " nil t))
5708         (error "No Message-ID in this article")
5709       (replace-match "Supersedes: " t t))
5710     (goto-char (point-max))
5711     (insert mail-header-separator)
5712     (widen)
5713     (when message-supersede-setup-function
5714       (funcall message-supersede-setup-function))
5715     (run-hooks 'message-supersede-setup-hook)
5716     (goto-char (point-min))
5717     (search-forward (concat "\n" mail-header-separator "\n") nil t)))
5718
5719 ;;;###autoload
5720 (defun message-recover ()
5721   "Reread contents of current buffer from its last auto-save file."
5722   (interactive)
5723   (let ((file-name (make-auto-save-file-name)))
5724     (cond ((save-window-excursion
5725              (if (not (eq system-type 'vax-vms))
5726                  (with-output-to-temp-buffer "*Directory*"
5727                    (with-current-buffer standard-output
5728                      (fundamental-mode)) ; for Emacs 20.4+
5729                    (buffer-disable-undo standard-output)
5730                    (let ((default-directory "/"))
5731                      (call-process
5732                       "ls" nil standard-output nil "-l" file-name))))
5733              (yes-or-no-p (format "Recover auto save file %s? " file-name)))
5734            (let ((buffer-read-only nil))
5735              (erase-buffer)
5736              (insert-file-contents file-name nil)))
5737           (t (error "message-recover cancelled")))))
5738
5739 ;;; Washing Subject:
5740
5741 (defun message-wash-subject (subject)
5742   "Remove junk like \"Re:\", \"(fwd)\", etc. added to subject string SUBJECT.
5743 Previous forwarders, replyers, etc. may add it."
5744   (with-temp-buffer
5745     (insert subject)
5746     (goto-char (point-min))
5747     ;; strip Re/Fwd stuff off the beginning
5748     (while (re-search-forward
5749             "\\([Rr][Ee]:\\|[Ff][Ww][Dd]\\(\\[[0-9]*\\]\\)?:\\|[Ff][Ww]:\\)" nil t)
5750       (replace-match ""))
5751
5752     ;; and gnus-style forwards [foo@bar.com] subject
5753     (goto-char (point-min))
5754     (while (re-search-forward "\\[[^ \t]*\\(@\\|\\.\\)[^ \t]*\\]" nil t)
5755       (replace-match ""))
5756
5757     ;; and off the end
5758     (goto-char (point-max))
5759     (while (re-search-backward "([Ff][Ww][Dd])" nil t)
5760       (replace-match ""))
5761
5762     ;; and finally, any whitespace that was left-over
5763     (goto-char (point-min))
5764     (while (re-search-forward "^[ \t]+" nil t)
5765       (replace-match ""))
5766     (goto-char (point-max))
5767     (while (re-search-backward "[ \t]+$" nil t)
5768       (replace-match ""))
5769
5770     (buffer-string)))
5771
5772 ;;; Forwarding messages.
5773
5774 (defvar message-forward-decoded-p nil
5775   "Non-nil means the original message is decoded.")
5776
5777 (defun message-forward-subject-author-subject (subject)
5778   "Generate a SUBJECT for a forwarded message.
5779 The form is: [Source] Subject, where if the original message was mail,
5780 Source is the sender, and if the original message was news, Source is
5781 the list of newsgroups is was posted to."
5782   (concat "["
5783           (let ((prefix (message-fetch-field "newsgroups")))
5784             (or prefix
5785                 (and (setq prefix (message-fetch-field "from"))
5786                      (nnheader-decode-from prefix))
5787                 "(nowhere)"))
5788           "] " subject))
5789
5790 (defun message-forward-subject-fwd (subject)
5791   "Generate a SUBJECT for a forwarded message.
5792 The form is: Fwd: Subject, where Subject is the original subject of
5793 the message."
5794   (concat "Fwd: " subject))
5795
5796 (defun message-make-forward-subject ()
5797   "Return a Subject header suitable for the message in the current buffer."
5798   (save-excursion
5799     (save-restriction
5800       (message-narrow-to-head-1)
5801       (let ((funcs message-make-forward-subject-function)
5802             (subject (message-fetch-field "Subject")))
5803         (setq subject
5804               (if subject
5805                   (if message-forward-decoded-p
5806                       subject
5807                     (nnheader-decode-subject subject))
5808                 ""))
5809         (if message-wash-forwarded-subjects
5810             (setq subject (message-wash-subject subject)))
5811         ;; Make sure funcs is a list.
5812         (and funcs
5813              (not (listp funcs))
5814              (setq funcs (list funcs)))
5815         ;; Apply funcs in order, passing subject generated by previous
5816         ;; func to the next one.
5817         (while funcs
5818           (when (message-functionp (car funcs))
5819             (setq subject (funcall (car funcs) subject)))
5820           (setq funcs (cdr funcs)))
5821         subject))))
5822
5823 ;;;###autoload
5824 (defun message-forward (&optional news)
5825   "Forward the current message via mail.
5826 Optional NEWS will use news to forward instead of mail."
5827   (interactive "P")
5828   (let ((cur (current-buffer))
5829         (subject (message-make-forward-subject)))
5830     (if news
5831         (message-news nil subject)
5832       (message-mail nil subject))
5833     (message-forward-make-body cur)))
5834
5835 ;;;###autoload
5836 (defun message-forward-make-body (forward-buffer)
5837   ;; Put point where we want it before inserting the forwarded
5838   ;; message.
5839   ;; Note that this function definition for T-gnus is totally different
5840   ;; from the original Gnus."
5841   (if message-forward-before-signature
5842       (message-goto-body)
5843     (goto-char (point-max)))
5844   ;; Make sure we're at the start of the line.
5845   (unless (bolp)
5846     (insert "\n"))
5847   ;; Narrow to the area we are to insert.
5848   (narrow-to-region (point) (point))
5849   ;; Insert the separators and the forwarded buffer.
5850   (insert message-forward-start-separator)
5851   (let ((art-beg (point)))
5852     (insert-buffer-substring forward-buffer)
5853     (goto-char (point-max))
5854     (insert message-forward-end-separator)
5855     (set-text-properties (point-min) (point-max) nil)
5856     ;; Remove all unwanted headers.
5857     (goto-char art-beg)
5858     (narrow-to-region (point) (if (search-forward "\n\n" nil t)
5859                                   (1- (point))
5860                                 (point)))
5861     (goto-char (point-min))
5862     (message-remove-header message-included-forward-headers t nil t)
5863     (widen)
5864     (message-position-point)))
5865
5866 ;;;###autoload
5867 (defun message-forward-rmail-make-body (forward-buffer)
5868   (save-window-excursion
5869     (set-buffer forward-buffer)
5870     ;; Rmail doesn't have rmail-msg-restore-non-pruned-header in Emacs
5871     ;; 20.  FIXIT, or we drop support for rmail in Emacs 20.
5872     (if (rmail-msg-is-pruned)
5873         (rmail-msg-restore-non-pruned-header)))
5874   (message-forward-make-body forward-buffer))
5875
5876 ;;;###autoload
5877 (defun message-insinuate-rmail ()
5878   "Let RMAIL uses message to forward."
5879   (interactive)
5880   (setq rmail-enable-mime-composing t)
5881   (setq rmail-insert-mime-forwarded-message-function
5882         'message-forward-rmail-make-body))
5883
5884 ;;;###autoload
5885 (defun message-resend (address)
5886   "Resend the current article to ADDRESS."
5887   (interactive
5888    (list (message-read-from-minibuffer "Resend message to: ")))
5889   (message "Resending message to %s..." address)
5890   (save-excursion
5891     (let ((cur (current-buffer))
5892           beg)
5893       ;; We first set up a normal mail buffer.
5894       (unless (message-mail-user-agent)
5895         (set-buffer (get-buffer-create " *message resend*"))
5896         (erase-buffer)
5897         (let ((message-this-is-mail t)
5898               ;; avoid to turn-on-mime-edit
5899               message-setup-hook)
5900           (message-setup `((To . ,address)))))
5901       ;; Insert our usual headers.
5902       (message-generate-headers '(From Date To))
5903       (message-narrow-to-headers)
5904       ;; Rename them all to "Resent-*".
5905       (while (re-search-forward "^[A-Za-z]" nil t)
5906         (forward-char -1)
5907         (insert "Resent-"))
5908       (widen)
5909       (forward-line)
5910       (delete-region (point) (point-max))
5911       (setq beg (point))
5912       ;; Insert the message to be resent.
5913       (insert-buffer-substring cur)
5914       (goto-char (point-min))
5915       (search-forward "\n\n")
5916       (forward-char -1)
5917       (save-restriction
5918         (narrow-to-region beg (point))
5919         (message-remove-header message-ignored-resent-headers t)
5920         (goto-char (point-max)))
5921       (insert mail-header-separator)
5922       ;; Rename all old ("Also-")Resent headers.
5923       (while (re-search-backward "^\\(Also-\\)*Resent-" beg t)
5924         (beginning-of-line)
5925         (insert "Also-"))
5926       ;; Quote any "From " lines at the beginning.
5927       (goto-char beg)
5928       (when (looking-at "From ")
5929         (replace-match "X-From-Line: "))
5930       ;; Send it.
5931       (let ((message-encoding-buffer (current-buffer))
5932             (message-edit-buffer (current-buffer))
5933             message-required-mail-headers)
5934         (message-send-mail))
5935       (kill-buffer (current-buffer)))
5936     (message "Resending message to %s...done" address)))
5937
5938 (defun message-bounce-setup-for-mime-edit ()
5939   (set (make-local-variable 'message-setup-hook) nil)
5940   (mime-edit-again))
5941
5942 ;;;###autoload
5943 (defun message-bounce ()
5944   "Re-mail the current message.
5945 This only makes sense if the current message is a bounce message that
5946 contains some mail you have written which has been bounced back to
5947 you."
5948   (interactive)
5949   (let ((cur (current-buffer))
5950         boundary)
5951     (message-pop-to-buffer (message-buffer-name "bounce"))
5952     (insert-buffer-substring cur)
5953     (undo-boundary)
5954     (message-narrow-to-head)
5955     (if (and (message-fetch-field "MIME-Version")
5956              (setq boundary (message-fetch-field "Content-Type")))
5957         (if (string-match "boundary=\"\\([^\"]+\\)\"" boundary)
5958             (setq boundary (concat (match-string 1 boundary) " *\n"
5959                                    "Content-Type: message/rfc822"))
5960           (setq boundary nil)))
5961     (widen)
5962     (goto-char (point-min))
5963     (search-forward "\n\n" nil t)
5964     (if (or (and boundary
5965                  (re-search-forward boundary nil t)
5966                  (forward-line 2))
5967             (and (re-search-forward message-unsent-separator nil t)
5968                  (forward-line 1))
5969             (re-search-forward "^Return-Path:.*\n" nil t))
5970         ;; We remove everything before the bounced mail.
5971         (delete-region
5972          (point-min)
5973          (if (re-search-forward "^[^ \n\t]+:" nil t)
5974              (match-beginning 0)
5975            (point)))
5976       (when (re-search-backward "^.?From .*\n" nil t)
5977         (delete-region (match-beginning 0) (match-end 0))))
5978     (save-restriction
5979       (message-narrow-to-head-1)
5980       (message-remove-header message-ignored-bounced-headers t)
5981       (goto-char (point-max))
5982       (insert mail-header-separator))
5983     (when message-bounce-setup-function
5984       (funcall message-bounce-setup-function))
5985     (run-hooks 'message-bounce-setup-hook)
5986     (message-position-point)))
5987
5988 ;;;
5989 ;;; Interactive entry points for new message buffers.
5990 ;;;
5991
5992 ;;;###autoload
5993 (defun message-mail-other-window (&optional to subject)
5994   "Like `message-mail' command, but display mail buffer in another window."
5995   (interactive)
5996   (unless (message-mail-user-agent)
5997     (let ((pop-up-windows t)
5998           (special-display-buffer-names nil)
5999           (special-display-regexps nil)
6000           (same-window-buffer-names nil)
6001           (same-window-regexps nil))
6002       (message-pop-to-buffer (message-buffer-name "mail" to))))
6003   (let ((message-this-is-mail t))
6004     (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))
6005                    nil nil 'switch-to-buffer-other-window)))
6006
6007 ;;;###autoload
6008 (defun message-mail-other-frame (&optional to subject)
6009   "Like `message-mail' command, but display mail buffer in another frame."
6010   (interactive)
6011   (unless (message-mail-user-agent)
6012     (let ((pop-up-frames t)
6013           (special-display-buffer-names nil)
6014           (special-display-regexps nil)
6015           (same-window-buffer-names nil)
6016           (same-window-regexps nil))
6017       (message-pop-to-buffer (message-buffer-name "mail" to))))
6018   (let ((message-this-is-mail t))
6019     (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))
6020                    nil nil 'switch-to-buffer-other-frame)))
6021
6022 ;;;###autoload
6023 (defun message-news-other-window (&optional newsgroups subject)
6024   "Start editing a news article to be sent."
6025   (interactive)
6026   (let ((pop-up-windows t)
6027         (special-display-buffer-names nil)
6028         (special-display-regexps nil)
6029         (same-window-buffer-names nil)
6030         (same-window-regexps nil))
6031     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups)))
6032   (let ((message-this-is-news t))
6033     (message-setup `((Newsgroups . ,(or newsgroups ""))
6034                      (Subject . ,(or subject ""))))))
6035
6036 ;;;###autoload
6037 (defun message-news-other-frame (&optional newsgroups subject)
6038   "Start editing a news article to be sent."
6039   (interactive)
6040   (let ((pop-up-frames t)
6041         (special-display-buffer-names nil)
6042         (special-display-regexps nil)
6043         (same-window-buffer-names nil)
6044         (same-window-regexps nil))
6045     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups)))
6046   (let ((message-this-is-news t))
6047     (message-setup `((Newsgroups . ,(or newsgroups ""))
6048                      (Subject . ,(or subject ""))))))
6049
6050 ;;; underline.el
6051
6052 ;; This code should be moved to underline.el (from which it is stolen).
6053
6054 ;;;###autoload
6055 (defun bold-region (start end)
6056   "Bold all nonblank characters in the region.
6057 Works by overstriking characters.
6058 Called from program, takes two arguments START and END
6059 which specify the range to operate on."
6060   (interactive "r")
6061   (save-excursion
6062     (let ((end1 (make-marker)))
6063       (move-marker end1 (max start end))
6064       (goto-char (min start end))
6065       (while (< (point) end1)
6066         (or (looking-at "[_\^@- ]")
6067             (insert (char-after) "\b"))
6068         (forward-char 1)))))
6069
6070 ;;;###autoload
6071 (defun unbold-region (start end)
6072   "Remove all boldness (overstruck characters) in the region.
6073 Called from program, takes two arguments START and END
6074 which specify the range to operate on."
6075   (interactive "r")
6076   (save-excursion
6077     (let ((end1 (make-marker)))
6078       (move-marker end1 (max start end))
6079       (goto-char (min start end))
6080       (while (re-search-forward "\b" end1 t)
6081         (if (eq (char-after) (char-after (- (point) 2)))
6082             (delete-char -2))))))
6083
6084 (defalias 'message-exchange-point-and-mark 'exchange-point-and-mark)
6085
6086 ;; Support for toolbar
6087 (eval-when-compile
6088   (defvar tool-bar-map)
6089   (defvar tool-bar-mode))
6090
6091 (defun message-tool-bar-map ()
6092   (or message-tool-bar-map
6093       (setq message-tool-bar-map
6094             (and (fboundp 'tool-bar-add-item-from-menu)
6095                  tool-bar-mode
6096                  (let ((tool-bar-map (copy-keymap tool-bar-map))
6097                        (load-path (mm-image-load-path)))
6098                    ;; Zap some items which aren't so relevant and take
6099                    ;; up space.
6100                    (dolist (key '(print-buffer kill-buffer save-buffer
6101                                                write-file dired open-file))
6102                      (define-key tool-bar-map (vector key) nil))
6103                    (tool-bar-add-item-from-menu
6104                     'message-send-and-exit "mail_send" message-mode-map)
6105                    (tool-bar-add-item-from-menu
6106                     'message-kill-buffer "close" message-mode-map)
6107                    (tool-bar-add-item-from-menu
6108                     'message-dont-send "cancel" message-mode-map)
6109                    (tool-bar-add-item-from-menu
6110                     'mime-edit-insert-file "attach" message-mode-map)
6111                    (tool-bar-add-item-from-menu
6112                     'ispell-message "spell" message-mode-map)
6113                    (tool-bar-add-item-from-menu
6114                     'message-insert-importance-high "important"
6115                     message-mode-map)
6116                    (tool-bar-add-item-from-menu
6117                     'message-insert-importance-low "unimportant"
6118                     message-mode-map)
6119                    (tool-bar-add-item-from-menu
6120                     'message-insert-disposition-notification-to "receipt"
6121                     message-mode-map)
6122                    tool-bar-map)))))
6123
6124 ;;; Group name completion.
6125
6126 (defcustom message-newgroups-header-regexp
6127   "^\\(Newsgroups\\|Followup-To\\|Posted-To\\|Gcc\\):"
6128   "Regexp that match headers that lists groups."
6129   :group 'message
6130   :type 'regexp)
6131
6132 (defcustom message-completion-alist
6133   (list (cons message-newgroups-header-regexp 'message-expand-group)
6134         '("^\\(Resent-\\)?\\(To\\|B?Cc\\):" . message-expand-name))
6135   "Alist of (RE . FUN).  Use FUN for completion on header lines matching RE."
6136   :group 'message
6137   :type '(alist :key-type regexp :value-type function))
6138
6139 (defcustom message-tab-body-function nil
6140   "*Function to execute when `message-tab' (TAB) is executed in the body.
6141 If nil, the function bound in `text-mode-map' or `global-map' is executed."
6142   :group 'message
6143   :type 'function)
6144
6145 (defun message-tab ()
6146   "Complete names according to `message-completion-alist'.
6147 Execute function specified by `message-tab-body-function' when not in
6148 those headers."
6149   (interactive)
6150   (let ((alist message-completion-alist))
6151     (while (and alist
6152                 (let ((mail-abbrev-mode-regexp (caar alist)))
6153                   (not (mail-abbrev-in-expansion-header-p))))
6154       (setq alist (cdr alist)))
6155     (funcall (or (cdar alist) message-tab-body-function
6156                  (lookup-key text-mode-map "\t")
6157                  (lookup-key global-map "\t")
6158                  'indent-relative))))
6159
6160 (defun message-expand-group ()
6161   "Expand the group name under point."
6162   (let* ((b (save-excursion
6163               (save-restriction
6164                 (narrow-to-region
6165                  (save-excursion
6166                    (beginning-of-line)
6167                    (skip-chars-forward "^:")
6168                    (1+ (point)))
6169                  (point))
6170                 (skip-chars-backward "^, \t\n") (point))))
6171          (completion-ignore-case t)
6172          (string (buffer-substring b (progn (skip-chars-forward "^,\t\n ")
6173                                             (point))))
6174          (hashtb (and (boundp 'gnus-active-hashtb) gnus-active-hashtb))
6175          (completions (all-completions string hashtb))
6176          comp)
6177     (delete-region b (point))
6178     (cond
6179      ((= (length completions) 1)
6180       (if (string= (car completions) string)
6181           (progn
6182             (insert string)
6183             (message "Only matching group"))
6184         (insert (car completions))))
6185      ((and (setq comp (try-completion string hashtb))
6186            (not (string= comp string)))
6187       (insert comp))
6188      (t
6189       (insert string)
6190       (if (not comp)
6191           (message "No matching groups")
6192         (save-selected-window
6193           (pop-to-buffer "*Completions*")
6194           (buffer-disable-undo)
6195           (let ((buffer-read-only nil))
6196             (erase-buffer)
6197             (let ((standard-output (current-buffer)))
6198               (display-completion-list (sort completions 'string<)))
6199             (goto-char (point-min))
6200             (delete-region (point) (progn (forward-line 3) (point))))))))))
6201
6202 (defun message-expand-name ()
6203   (if (fboundp 'bbdb-complete-name)
6204       (bbdb-complete-name)
6205     (expand-abbrev)))
6206
6207 ;;; Help stuff.
6208
6209 (defun message-talkative-question (ask question show &rest text)
6210   "Call FUNCTION with argument QUESTION; optionally display TEXT... args.
6211 If SHOW is non-nil, the arguments TEXT... are displayed in a temp buffer.
6212 The following arguments may contain lists of values."
6213   (if (and show
6214            (setq text (message-flatten-list text)))
6215       (save-window-excursion
6216         (save-excursion
6217           (with-output-to-temp-buffer " *MESSAGE information message*"
6218             (set-buffer " *MESSAGE information message*")
6219             (fundamental-mode)          ; for Emacs 20.4+
6220             (mapcar 'princ text)
6221             (goto-char (point-min))))
6222         (funcall ask question))
6223     (funcall ask question)))
6224
6225 (defun message-flatten-list (list)
6226   "Return a new, flat list that contains all elements of LIST.
6227
6228 \(message-flatten-list '(1 (2 3 (4 5 (6))) 7))
6229 => (1 2 3 4 5 6 7)"
6230   (cond ((consp list)
6231          (apply 'append (mapcar 'message-flatten-list list)))
6232         (list
6233          (list list))))
6234
6235 (defun message-generate-new-buffer-clone-locals (name &optional varstr)
6236   "Create and return a buffer with name based on NAME using `generate-new-buffer.'
6237 Then clone the local variables and values from the old buffer to the
6238 new one, cloning only the locals having a substring matching the
6239 regexp varstr."
6240   (let ((oldbuf (current-buffer)))
6241     (save-excursion
6242       (set-buffer (generate-new-buffer name))
6243       (message-clone-locals oldbuf varstr)
6244       (current-buffer))))
6245
6246 (defun message-clone-locals (buffer &optional varstr)
6247   "Clone the local variables from BUFFER to the current buffer."
6248   (let ((locals (save-excursion
6249                   (set-buffer buffer)
6250                   (buffer-local-variables)))
6251         (regexp
6252          "^\\(gnus\\|nn\\|message\\|user-\\(mail-address\\|full-name\\)\\)"))
6253     (mapcar
6254      (lambda (local)
6255        (when (and (consp local)
6256                   (car local)
6257                   (string-match regexp (symbol-name (car local)))
6258                   (or (null varstr)
6259                       (string-match varstr (symbol-name (car local)))))
6260          (ignore-errors
6261            (set (make-local-variable (car local))
6262                 (cdr local)))))
6263      locals)))
6264
6265
6266 ;;; @ for MIME Edit mode
6267 ;;;
6268
6269 (defun message-maybe-encode ()
6270   (when message-mime-mode
6271     ;; Inherit the buffer local variable `mime-edit-pgp-processing'.
6272     (let ((pgp-processing (with-current-buffer message-edit-buffer
6273                             mime-edit-pgp-processing)))
6274       (setq mime-edit-pgp-processing pgp-processing))
6275     (run-hooks 'mime-edit-translate-hook)
6276     (if (catch 'mime-edit-error
6277           (save-excursion
6278             (mime-edit-pgp-enclose-buffer)
6279             (mime-edit-translate-body)))
6280         (error "Translation error!"))
6281     (run-hooks 'mime-edit-exit-hook)))
6282
6283 (defun message-mime-insert-article (&optional full-headers)
6284   (interactive "P")
6285   (let ((message-cite-function 'mime-edit-inserted-message-filter)
6286         (message-reply-buffer
6287          (message-get-parameter-with-eval 'original-buffer))
6288         (start (point)))
6289     (message-yank-original nil)
6290     (save-excursion
6291       (narrow-to-region (goto-char start)
6292                         (if (search-forward "\n\n" nil t)
6293                             (1- (point))
6294                           (point-max)))
6295       (goto-char (point-min))
6296       (let ((message-included-forward-headers
6297              (if full-headers "" message-included-forward-headers)))
6298         (message-remove-header message-included-forward-headers t nil t))
6299       (widen))))
6300
6301 (set-alist 'mime-edit-message-inserter-alist
6302            'message-mode (function message-mime-insert-article))
6303
6304 ;;; Miscellaneous functions
6305
6306 ;; stolen (and renamed) from nnheader.el
6307 (static-if (fboundp 'subst-char-in-string)
6308     (defsubst message-replace-chars-in-string (string from to)
6309       (subst-char-in-string from to string))
6310   (defun message-replace-chars-in-string (string from to)
6311     "Replace characters in STRING from FROM to TO."
6312     (let ((string (substring string 0)) ;Copy string.
6313           (len (length string))
6314           (idx 0))
6315       ;; Replace all occurrences of FROM with TO.
6316       (while (< idx len)
6317         (when (= (aref string idx) from)
6318           (aset string idx to))
6319         (setq idx (1+ idx)))
6320       string)))
6321
6322 ;;;
6323 ;;; MIME functions
6324 ;;;
6325
6326 (defvar message-inhibit-body-encoding t)
6327
6328 (defun message-encode-message-body ()
6329   (unless message-inhibit-body-encoding
6330     (let ((mail-parse-charset (or mail-parse-charset
6331                                   message-default-charset))
6332           (case-fold-search t)
6333           lines content-type-p)
6334       (message-goto-body)
6335       (save-restriction
6336         (narrow-to-region (point) (point-max))
6337         (let ((new (mml-generate-mime)))
6338           (when new
6339             (delete-region (point-min) (point-max))
6340             (insert new)
6341             (goto-char (point-min))
6342             (if (eq (aref new 0) ?\n)
6343                 (delete-char 1)
6344               (search-forward "\n\n")
6345               (setq lines (buffer-substring (point-min) (1- (point))))
6346               (delete-region (point-min) (point))))))
6347       (save-restriction
6348         (message-narrow-to-headers-or-head)
6349         (message-remove-header "Mime-Version")
6350         (goto-char (point-max))
6351         (insert "MIME-Version: 1.0\n")
6352         (when lines
6353           (insert lines))
6354         (setq content-type-p
6355               (or mml-boundary
6356                   (re-search-backward "^Content-Type:" nil t))))
6357       (save-restriction
6358         (message-narrow-to-headers-or-head)
6359         (message-remove-first-header "Content-Type")
6360         (message-remove-first-header "Content-Transfer-Encoding"))
6361       ;; We always make sure that the message has a Content-Type
6362       ;; header.  This is because some broken MTAs and MUAs get
6363       ;; awfully confused when confronted with a message with a
6364       ;; MIME-Version header and without a Content-Type header.  For
6365       ;; instance, Solaris' /usr/bin/mail.
6366       (unless content-type-p
6367         (goto-char (point-min))
6368         ;; For unknown reason, MIME-Version doesn't exist.
6369         (when (re-search-forward "^MIME-Version:" nil t)
6370           (forward-line 1)
6371           (insert "Content-Type: text/plain; charset=us-ascii\n"))))))
6372
6373 (defun message-read-from-minibuffer (prompt &optional initial-contents)
6374   "Read from the minibuffer while providing abbrev expansion."
6375   (if (fboundp 'mail-abbrevs-setup)
6376       (let ((mail-abbrev-mode-regexp "")
6377             (minibuffer-setup-hook 'mail-abbrevs-setup)
6378             (minibuffer-local-map message-minibuffer-local-map))
6379         (read-from-minibuffer prompt initial-contents))
6380     (let ((minibuffer-setup-hook 'mail-abbrev-minibuffer-setup-hook)
6381           (minibuffer-local-map message-minibuffer-local-map))
6382       (read-string prompt initial-contents))))
6383
6384 (defun message-use-alternative-email-as-from ()
6385   (require 'mail-utils)
6386   (let* ((fields '("To" "Cc"))
6387          (emails
6388           (split-string
6389            (mail-strip-quoted-names
6390             (mapconcat 'message-fetch-reply-field fields ","))
6391            "[ \f\t\n\r\v,]+"))
6392          email)
6393     (while emails
6394       (if (string-match message-alternative-emails (car emails))
6395           (setq email (car emails)
6396                 emails nil))
6397       (pop emails))
6398     (unless (or (not email) (equal email user-mail-address))
6399       (goto-char (point-max))
6400       (insert "From: " email "\n"))))
6401
6402 (defun message-options-get (symbol)
6403   (cdr (assq symbol message-options)))
6404
6405 (defun message-options-set (symbol value)
6406   (let ((the-cons (assq symbol message-options)))
6407     (if the-cons
6408         (if value
6409             (setcdr the-cons value)
6410           (setq message-options (delq the-cons message-options)))
6411       (and value
6412            (push (cons symbol value) message-options))))
6413   value)
6414
6415 (defun message-options-set-recipient ()
6416   (save-restriction
6417     (message-narrow-to-headers-or-head)
6418     (message-options-set 'message-sender
6419                          (mail-strip-quoted-names
6420                           (message-fetch-field "from")))
6421     (message-options-set 'message-recipients
6422                          (mail-strip-quoted-names
6423                           (let ((to (message-fetch-field "to"))
6424                                 (cc (message-fetch-field "cc"))
6425                                 (bcc (message-fetch-field "bcc")))
6426                             (concat
6427                              (or to "")
6428                              (if (and to cc) ", ")
6429                              (or cc "")
6430                              (if (and (or to cc) bcc) ", ")
6431                              (or bcc "")))))))
6432
6433 (when (featurep 'xemacs)
6434   (require 'messagexmas)
6435   (message-xmas-redefine))
6436
6437 (defun message-save-drafts ()
6438   "Postponing the message."
6439   (interactive)
6440   (message "Saving %s..." buffer-file-name)
6441   (let ((reply-headers message-reply-headers)
6442         (buffer (current-buffer)))
6443     (with-temp-file buffer-file-name
6444       (insert-buffer-substring buffer)
6445       (setq message-reply-headers reply-headers)
6446       (message-generate-headers '((optional . In-Reply-To)))
6447       (let ((mime-header-encode-method-alist
6448              '((eword-encode-unstructured-field-body))))
6449         (mime-edit-translate-buffer)))
6450     (set-buffer-modified-p nil))
6451   (message "Saving %s...done" buffer-file-name))
6452
6453 (provide 'message)
6454
6455 (run-hooks 'message-load-hook)
6456
6457 ;; Local Variables:
6458 ;; coding: iso-8859-1
6459 ;; End:
6460
6461 ;;; message.el ends here