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