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