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