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