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