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