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