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