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