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