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