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