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