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