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