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