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