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