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