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