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