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