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