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