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