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