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