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