Sync up with Semi-gnus 6.8.15.
[elisp/gnus.git-] / lisp / message.el
1 ;;; message.el --- composing mail and news messages
2 ;; Copyright (C) 1996,97,98 Free Software Foundation, Inc.
3
4 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
5 ;;      MORIOKA Tomohiko <morioka@jaist.ac.jp>
6 ;;      Shuhei KOBAYASHI <shuhei-k@jaist.ac.jp>
7 ;;      Keiichi Suzuki <kei-suzu@mail.wbs.ne.jp>
8 ;; Keywords: mail, news, MIME
9
10 ;; This file is part of GNU Emacs.
11
12 ;; GNU Emacs is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 2, or (at your option)
15 ;; any later version.
16
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20 ;; GNU General Public License for more details.
21
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
24 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
25 ;; Boston, MA 02111-1307, USA.
26
27 ;;; Commentary:
28
29 ;; This mode provides mail-sending facilities from within Emacs.  It
30 ;; consists mainly of large chunks of code from the sendmail.el,
31 ;; gnus-msg.el and rnewspost.el files.
32
33 ;;; Code:
34
35 (eval-when-compile
36   (require 'cl)
37   (require 'smtp)
38   )
39
40 (require 'mailheader)
41 (require 'nnheader)
42 (require 'timezone)
43 (require 'easymenu)
44 (require 'custom)
45 (if (string-match "XEmacs\\|Lucid" emacs-version)
46     (require 'mail-abbrevs)
47   (require 'mailabbrev))
48 (require 'mime-edit)
49
50 (defgroup message '((user-mail-address custom-variable)
51                     (user-full-name custom-variable))
52   "Mail and news message composing."
53   :link '(custom-manual "(message)Top")
54   :group 'mail
55   :group 'news)
56
57 (put 'user-mail-address 'custom-type 'string)
58 (put 'user-full-name 'custom-type 'string)
59
60 (defgroup message-various nil
61   "Various Message Variables"
62   :link '(custom-manual "(message)Various Message Variables")
63   :group 'message)
64
65 (defgroup message-buffers nil
66   "Message Buffers"
67   :link '(custom-manual "(message)Message Buffers")
68   :group 'message)
69
70 (defgroup message-sending nil
71   "Message Sending"
72   :link '(custom-manual "(message)Sending Variables")
73   :group 'message)
74
75 (defgroup message-interface nil
76   "Message Interface"
77   :link '(custom-manual "(message)Interface")
78   :group 'message)
79
80 (defgroup message-forwarding nil
81   "Message Forwarding"
82   :link '(custom-manual "(message)Forwarding")
83   :group 'message-interface)
84
85 (defgroup message-insertion nil
86   "Message Insertion"
87   :link '(custom-manual "(message)Insertion")
88   :group 'message)
89
90 (defgroup message-headers nil
91   "Message Headers"
92   :link '(custom-manual "(message)Message Headers")
93   :group 'message)
94
95 (defgroup message-news nil
96   "Composing News Messages"
97   :group 'message)
98
99 (defgroup message-mail nil
100   "Composing Mail Messages"
101   :group 'message)
102
103 (defgroup message-faces nil
104   "Faces used for message composing."
105   :group 'message
106   :group 'faces)
107
108 (defgroup message-frames nil
109   "Message frames"
110   :group 'message)
111
112 (defcustom message-directory "~/Mail/"
113   "*Directory from which all other mail file variables are derived."
114   :group 'message-various
115   :type 'directory)
116
117 (defcustom message-max-buffers 10
118   "*How many buffers to keep before starting to kill them off."
119   :group 'message-buffers
120   :type 'integer)
121
122 (defcustom message-send-rename-function nil
123   "Function called to rename the buffer after sending it."
124   :group 'message-buffers
125   :type 'function)
126
127 (defcustom message-fcc-handler-function 'message-output
128   "*A function called to save outgoing articles.
129 This function will be called with the name of the file to store the
130 article in.  The default function is `message-output' which saves in Unix
131 mailbox format."
132   :type '(radio (function-item message-output)
133                 (function :tag "Other"))
134   :group 'message-sending)
135
136 (defcustom message-encode-function 'message-maybe-encode
137   "*A function called to encode messages."
138   :group 'message-sending
139   :type 'function)
140
141 (defcustom message-courtesy-message
142   "The following message is a courtesy copy of an article\nthat has been posted to %s as well.\n\n"
143   "*This is inserted at the start of a mailed copy of a posted message.
144 If the string contains the format spec \"%s\", the Newsgroups
145 the article has been posted to will be inserted there.
146 If this variable is nil, no such courtesy message will be added."
147   :group 'message-sending
148   :type 'string)
149
150 (defcustom message-ignored-bounced-headers "^\\(Received\\|Return-Path\\):"
151   "*Regexp that matches headers to be removed in resent bounced mail."
152   :group 'message-interface
153   :type 'regexp)
154
155 ;;;###autoload
156 (defcustom message-from-style 'default
157   "*Specifies how \"From\" headers look.
158
159 If `nil', they contain just the return address like:
160         king@grassland.com
161 If `parens', they look like:
162         king@grassland.com (Elvis Parsley)
163 If `angles', they look like:
164         Elvis Parsley <king@grassland.com>
165
166 Otherwise, most addresses look like `angles', but they look like
167 `parens' if `angles' would need quoting and `parens' would not."
168   :type '(choice (const :tag "simple" nil)
169                  (const parens)
170                  (const angles)
171                  (const default))
172   :group 'message-headers)
173
174 (defcustom message-syntax-checks nil
175   ; Guess this one shouldn't be easy to customize...
176   "*Controls what syntax checks should not be performed on outgoing posts.
177 To disable checking of long signatures, for instance, add
178  `(signature . disabled)' to this list.
179
180 Don't touch this variable unless you really know what you're doing.
181
182 Checks include subject-cmsg multiple-headers sendsys message-id from
183 long-lines control-chars size new-text redirected-followup signature
184 approved sender empty empty-headers message-id from subject
185 shorten-followup-to existing-newsgroups buffer-file-name unchanged."
186   :group 'message-news)
187
188 (defcustom message-required-news-headers
189   '(From Newsgroups Subject Date Message-ID
190          (optional . Organization) Lines
191          (optional . User-Agent))
192   "*Headers to be generated or prompted for when posting an article.
193 RFC977 and RFC1036 require From, Date, Newsgroups, Subject,
194 Message-ID.  Organization, Lines, In-Reply-To, Expires, and
195 User-Agent are optional.  If don't you want message to insert some
196 header, remove it from this list."
197   :group 'message-news
198   :group 'message-headers
199   :type '(repeat sexp))
200
201 (defcustom message-required-mail-headers
202   '(From Subject Date (optional . In-Reply-To) Message-ID Lines
203          (optional . User-Agent))
204   "*Headers to be generated or prompted for when mailing a message.
205 RFC822 required that From, Date, To, Subject and Message-ID be
206 included.  Organization, Lines and User-Agent are optional."
207   :group 'message-mail
208   :group 'message-headers
209   :type '(repeat sexp))
210
211 (defcustom message-deletable-headers '(Message-ID Date Lines)
212   "Headers to be deleted if they already exist and were generated by message previously."
213   :group 'message-headers
214   :type 'sexp)
215
216 (defcustom message-ignored-news-headers
217   "^NNTP-Posting-Host:\\|^Xref:\\|^[BGF]cc:\\|^Resent-Fcc:"
218   "*Regexp of headers to be removed unconditionally before posting."
219   :group 'message-news
220   :group 'message-headers
221   :type 'regexp)
222
223 (defcustom message-ignored-mail-headers "^[GF]cc:\\|^Resent-Fcc:\\|^Xref:"
224   "*Regexp of headers to be removed unconditionally before mailing."
225   :group 'message-mail
226   :group 'message-headers
227   :type 'regexp)
228
229 (defcustom message-ignored-supersedes-headers "^Path:\\|^Date\\|^NNTP-Posting-Host:\\|^Xref:\\|^Lines:\\|^Received:\\|^X-From-Line:\\|^X-Trace:\\|^X-Complaints-To:\\|Return-Path:\\|^Supersedes:"
230   "*Header lines matching this regexp will be deleted before posting.
231 It's best to delete old Path and Date headers before posting to avoid
232 any confusion."
233   :group 'message-interface
234   :type 'regexp)
235
236 (defcustom message-subject-re-regexp "^[ \t]*\\([Rr][Ee]:[ \t]*\\)*[ \t]*"
237   "*Regexp matching \"Re: \" in the subject line."
238   :group 'message-various
239   :type 'regexp)
240
241 ;;; Some sender agents encode the whole subject including leading "Re: ".
242 ;;; And if followup agent does not decode it for some reason (e.g. unknown
243 ;;; charset) and just add a new "Re: " in front of the encoded-word, the
244 ;;; result will contain multiple "Re: "'s.
245 (defcustom message-subject-encoded-re-regexp
246   (concat
247    "^[ \t]*"
248    (regexp-quote "=?")
249    "[-!#$%&'*+0-9A-Z^_`a-z{|}~]+" ; charset
250    (regexp-quote "?")
251    "\\("
252    "[Bb]" (regexp-quote "?") ; B encoding
253    "\\(\\(CQk\\|CSA\\|IAk\\|ICA\\)[Jg]\\)*" ; \([ \t][ \t][ \t]\)*
254    "\\("
255    "[Uc][km]U6" ; [Rr][Ee]:
256    "\\|"
257    "\\(C[VX]\\|I[FH]\\)J[Fl]O[g-v]" ; [ \t][Rr][Ee]:
258    "\\|"
259    "\\(CQl\\|CSB\\|IAl\\|ICB\\)[Sy][RZ]T[o-r]" ; [ \t][ \t][Rr][Ee]:
260    "\\)"
261    "\\|"
262    "[Qb]" (regexp-quote "?") ; Q encoding
263    "\\(_\\|=09\\|=20\\)*"
264    "\\([Rr]\\|=[57]2\\)\\([Ee]\\|=[46]5\\)\\(:\\|=3[Aa]\\)"
265    "\\)"
266    )
267   "*Regexp matching \"Re: \" in the subject line.
268 Unlike `message-subject-re-regexp', this regexp matches \"Re: \" within
269 an encoded-word."
270   :group 'message-various
271   :type 'regexp)
272
273 (defcustom message-use-subject-re t
274   "*If t, remove any (buggy) \"Re: \"'s from the subject of the precursor
275 and add a new \"Re: \".  If it is nil, use the subject \"as-is\".  If it
276 is the symbol `guess', try to detect \"Re: \" within an encoded-word."
277   :group 'message-various
278   :type '(choice (const :tag "off" nil)
279                  (const :tag "on" t)
280                  (const guess)))
281
282 ;;;###autoload
283 (defcustom message-signature-separator "^-- *$"
284   "Regexp matching the signature separator."
285   :type 'regexp
286   :group 'message-various)
287
288 (defcustom message-elide-elipsis "\n[...]\n\n"
289   "*The string which is inserted for elided text."
290   :type 'string
291   :group 'message-various)
292
293 (defcustom message-interactive nil
294   "Non-nil means when sending a message wait for and display errors.
295 nil means let mailer mail back a message to report errors."
296   :group 'message-sending
297   :group 'message-mail
298   :type 'boolean)
299
300 (defcustom message-generate-new-buffers t
301   "*Non-nil means that a new message buffer will be created whenever `message-setup' is called.
302 If this is a function, call that function with three parameters:  The type,
303 the to address and the group name.  (Any of these may be nil.)  The function
304 should return the new buffer name."
305   :group 'message-buffers
306   :type '(choice (const :tag "off" nil)
307                  (const :tag "on" t)
308                  (function fun)))
309
310 (defcustom message-kill-buffer-on-exit nil
311   "*Non-nil means that the message buffer will be killed after sending a message."
312   :group 'message-buffers
313   :type 'boolean)
314
315 (defvar gnus-local-organization)
316 (defcustom message-user-organization
317   (or (and (boundp 'gnus-local-organization)
318            (stringp gnus-local-organization)
319            gnus-local-organization)
320       (getenv "ORGANIZATION")
321       t)
322   "*String to be used as an Organization header.
323 If t, use `message-user-organization-file'."
324   :group 'message-headers
325   :type '(choice string
326                  (const :tag "consult file" t)))
327
328 ;;;###autoload
329 (defcustom message-user-organization-file "/usr/lib/news/organization"
330   "*Local news organization file."
331   :type 'file
332   :group 'message-headers)
333
334 (defcustom message-forward-start-separator
335   (concat (mime-make-tag "message" "rfc822") "\n")
336   "*Delimiter inserted before forwarded messages."
337   :group 'message-forwarding
338   :type 'string)
339
340 (defcustom message-forward-end-separator
341   ""
342   "*Delimiter inserted after forwarded messages."
343   :group 'message-forwarding
344   :type 'string)
345
346 (defcustom message-signature-before-forwarded-message t
347   "*If non-nil, put the signature before any included forwarded message."
348   :group 'message-forwarding
349   :type 'boolean)
350
351 (defcustom message-included-forward-headers
352   "^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:"
353   "*Regexp matching headers to be included in forwarded messages."
354   :group 'message-forwarding
355   :type 'regexp)
356
357 (defcustom message-make-forward-subject-function 
358   'message-forward-subject-author-subject
359  "*A list of functions that are called to generate a subject header for forwarded messages.
360 The subject generated by the previous function is passed into each
361 successive function.
362
363 The provided functions are:
364
365 * message-forward-subject-author-subject (Source of article (author or
366       newsgroup)), in brackets followed by the subject
367 * message-forward-subject-fwd (Subject of article with 'Fwd:' prepended
368       to it."
369  :group 'message-forwarding
370  :type '(radio (function-item message-forward-subject-author-subject)
371                (function-item message-forward-subject-fwd)))
372
373 (defcustom message-wash-forwarded-subjects nil
374   "*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."
375   :group 'message-forwarding
376   :type 'boolean)
377
378 (defcustom message-ignored-resent-headers "^Return-Receipt"
379   "*All headers that match this regexp will be deleted when resending a message."
380   :group 'message-interface
381   :type 'regexp)
382
383 (defcustom message-ignored-cited-headers "."
384   "*Delete these headers from the messages you yank."
385   :group 'message-insertion
386   :type 'regexp)
387
388 (defcustom message-cancel-message "I am canceling my own article."
389   "Message to be inserted in the cancel message."
390   :group 'message-interface
391   :type 'string)
392
393 ;; Useful to set in site-init.el
394 ;;;###autoload
395 (defcustom message-send-mail-function 'message-send-mail-with-sendmail
396   "Function to call to send the current buffer as mail.
397 The headers should be delimited by a line whose contents match the
398 variable `mail-header-separator'.
399
400 Legal values include `message-send-mail-with-sendmail' (the default),
401 `message-send-mail-with-mh', `message-send-mail-with-qmail' and
402 `message-send-mail-with-smtp'."
403   :type '(radio (function-item message-send-mail-with-sendmail)
404                 (function-item message-send-mail-with-mh)
405                 (function-item message-send-mail-with-qmail)
406                 (function-item message-send-mail-with-smtp)
407                 (function :tag "Other"))
408   :group 'message-sending
409   :group 'message-mail)
410
411 ;; 1997-09-29 by MORIOKA Tomohiko
412 (defcustom message-send-news-function 'message-send-news-with-gnus
413   "Function to call to send the current buffer as news.
414 The headers should be delimited by a line whose contents match the
415 variable `mail-header-separator'."
416   :group 'message-sending
417   :group 'message-news
418   :type 'function)
419
420 (defcustom message-reply-to-function nil
421   "Function that should return a list of headers.
422 This function should pick out addresses from the To, Cc, and From headers
423 and respond with new To and Cc headers."
424   :group 'message-interface
425   :type 'function)
426
427 (defcustom message-wide-reply-to-function nil
428   "Function that should return a list of headers.
429 This function should pick out addresses from the To, Cc, and From headers
430 and respond with new To and Cc headers."
431   :group 'message-interface
432   :type 'function)
433
434 (defcustom message-followup-to-function nil
435   "Function that should return a list of headers.
436 This function should pick out addresses from the To, Cc, and From headers
437 and respond with new To and Cc headers."
438   :group 'message-interface
439   :type 'function)
440
441 (defcustom message-use-followup-to 'ask
442   "*Specifies what to do with Followup-To header.
443 If nil, always ignore the header.  If it is t, use its value, but
444 query before using the \"poster\" value.  If it is the symbol `ask',
445 always query the user whether to use the value.  If it is the symbol
446 `use', always use the value."
447   :group 'message-interface
448   :type '(choice (const :tag "ignore" nil)
449                  (const :tag "maybe" t)
450                  (const :tag "always" use)
451                  (const :tag "ask" ask)))
452
453 (defcustom message-use-mail-copies-to 'ask
454   "*Specifies what to do with Mail-Copies-To header.
455 If nil, always ignore the header.  If it is t, use its value, but
456 query before using the value other than \"always\" or \"never\".
457 If it is the symbol `ask', always query the user whether to use
458 the value.  If it is the symbol `use', always use the value."
459   :group 'message-interface
460   :type '(choice (const :tag "ignore" nil)
461                  (const :tag "maybe" t)
462                  (const :tag "always" use)
463                  (const :tag "ask" ask)))
464
465 (defcustom message-use-mail-followup-to 'ask
466   "*Specifies what to do with Mail-Followup-To header.
467 If nil, always ignore the header.  If it is the symbol `ask', always
468 query the user whether to use the value.  If it is t or the symbol
469 `use', always use the value."
470   :group 'message-interface
471   :type '(choice (const :tag "ignore" nil)
472                  (const :tag "maybe" t)
473                  (const :tag "always" use)
474                  (const :tag "ask" ask)))
475
476 ;;; XXX: 'ask and 'use are not implemented yet.
477 (defcustom message-use-mail-reply-to 'ask
478   "*Specifies what to do with Mail-Reply-To/Reply-To header.
479 If nil, always ignore the header.  If it is t or the symbol `use', use
480 its value.  If it is the symbol `ask', always query the user whether to
481 use the value.  Not that if \"Reply-To\" is marked as \"broken\", its value
482 is never used."
483   :group 'message-interface
484   :type '(choice (const :tag "ignore" nil)
485                  (const :tag "maybe" t)
486                  (const :tag "always" use)
487                  (const :tag "ask" ask)))
488
489 ;; stuff relating to broken sendmail in MMDF
490 (defcustom message-sendmail-f-is-evil nil
491   "*Non-nil means that \"-f username\" should not be added to the sendmail
492 command line, because it is even more evil than leaving it out."
493   :group 'message-sending
494   :type 'boolean)
495
496 ;; qmail-related stuff
497 (defcustom message-qmail-inject-program "/var/qmail/bin/qmail-inject"
498   "Location of the qmail-inject program."
499   :group 'message-sending
500   :type 'file)
501
502 (defcustom message-qmail-inject-args nil
503   "Arguments passed to qmail-inject programs.
504 This should be a list of strings, one string for each argument.
505
506 For e.g., if you wish to set the envelope sender address so that bounces
507 go to the right place or to deal with listserv's usage of that address, you
508 might set this variable to '(\"-f\" \"you@some.where\")."
509   :group 'message-sending
510   :type '(repeat string))
511
512 (defvar gnus-post-method)
513 (defvar gnus-select-method)
514 (defcustom message-post-method
515   (cond ((and (boundp 'gnus-post-method)
516               (listp gnus-post-method)
517               gnus-post-method)
518          gnus-post-method)
519         ((boundp 'gnus-select-method)
520          gnus-select-method)
521         (t '(nnspool "")))
522   "*Method used to post news.
523 Note that when posting from inside Gnus, for instance, this
524 variable isn't used."
525   :group 'message-news
526   :group 'message-sending
527   ;; This should be the `gnus-select-method' widget, but that might
528   ;; create a dependence to `gnus.el'.
529   :type 'sexp)
530
531 (defcustom message-generate-headers-first nil
532   "*If non-nil, generate all possible headers before composing."
533   :group 'message-headers
534   :type 'boolean)
535
536 (defcustom message-setup-hook
537   '(message-maybe-setup-default-charset turn-on-mime-edit)
538   "Normal hook, run each time a new outgoing message is initialized.
539 The function `message-setup' runs this hook."
540   :group 'message-various
541   :type 'hook)
542
543 (defcustom message-signature-setup-hook nil
544   "Normal hook, run each time a new outgoing message is initialized.
545 It is run after the headers have been inserted and before
546 the signature is inserted."
547   :group 'message-various
548   :type 'hook)
549
550 (defcustom message-mode-hook nil
551   "Hook run in message mode buffers."
552   :group 'message-various
553   :type 'hook)
554
555 (defcustom message-header-hook '(eword-encode-header)
556   "Hook run in a message mode buffer narrowed to the headers."
557   :group 'message-various
558   :type 'hook)
559
560 (defcustom message-header-setup-hook nil
561   "Hook called narrowed to the headers when setting up a message buffer."
562   :group 'message-various
563   :type 'hook)
564
565 ;;;###autoload
566 (defcustom message-citation-line-function 'message-insert-citation-line
567   "*Function called to insert the \"Whomever writes:\" line."
568   :type 'function
569   :group 'message-insertion)
570
571 ;;;###autoload
572 (defcustom message-yank-prefix "> "
573   "*Prefix inserted on the lines of yanked messages.
574 nil means use indentation."
575   :type 'string
576   :group 'message-insertion)
577
578 (defcustom message-indentation-spaces 3
579   "*Number of spaces to insert at the beginning of each cited line.
580 Used by `message-yank-original' via `message-yank-cite'."
581   :group 'message-insertion
582   :type 'integer)
583
584 ;;;###autoload
585 (defcustom message-cite-function 'message-cite-original
586   "*Function for citing an original message.
587 Predefined functions include `message-cite-original' and
588 `message-cite-original-without-signature'.
589 Note that `message-cite-original' uses `mail-citation-hook' if that is non-nil."
590   :type '(radio (function-item message-cite-original)
591                 (function-item sc-cite-original)
592                 (function :tag "Other"))
593   :group 'message-insertion)
594
595 ;;;###autoload
596 (defcustom message-indent-citation-function 'message-indent-citation
597   "*Function for modifying a citation just inserted in the mail buffer.
598 This can also be a list of functions.  Each function can find the
599 citation between (point) and (mark t).  And each function should leave
600 point and mark around the citation text as modified."
601   :type 'function
602   :group 'message-insertion)
603
604 (defvar message-abbrevs-loaded nil)
605
606 ;;;###autoload
607 (defcustom message-signature t
608   "*String to be inserted at the end of the message buffer.
609 If t, the `message-signature-file' file will be inserted instead.
610 If a function, the result from the function will be used instead.
611 If a form, the result from the form will be used instead."
612   :type 'sexp
613   :group 'message-insertion)
614
615 ;;;###autoload
616 (defcustom message-signature-file "~/.signature"
617   "*File containing the text inserted at end of message buffer."
618   :type 'file
619   :group 'message-insertion)
620
621 (defcustom message-distribution-function nil
622   "*Function called to return a Distribution header."
623   :group 'message-news
624   :group 'message-headers
625   :type 'function)
626
627 (defcustom message-expires 14
628   "Number of days before your article expires."
629   :group 'message-news
630   :group 'message-headers
631   :link '(custom-manual "(message)News Headers")
632   :type 'integer)
633
634 (defcustom message-user-path nil
635   "If nil, use the NNTP server name in the Path header.
636 If stringp, use this; if non-nil, use no host name (user name only)."
637   :group 'message-news
638   :group 'message-headers
639   :link '(custom-manual "(message)News Headers")
640   :type '(choice (const :tag "nntp" nil)
641                  (string :tag "name")
642                  (sexp :tag "none" :format "%t" t)))
643
644 (defvar message-reply-buffer nil)
645 (defvar message-reply-headers nil)
646 (defvar message-sent-message-via nil)
647 (defvar message-checksum nil)
648 (defvar message-send-actions nil
649   "A list of actions to be performed upon successful sending of a message.")
650 (defvar message-exit-actions nil
651   "A list of actions to be performed upon exiting after sending a message.")
652 (defvar message-kill-actions nil
653   "A list of actions to be performed before killing a message buffer.")
654 (defvar message-postpone-actions nil
655   "A list of actions to be performed after postponing a message.")
656 (defvar message-original-frame nil)
657
658 (define-widget 'message-header-lines 'text
659   "All header lines must be LFD terminated."
660   :format "%t:%n%v"
661   :valid-regexp "^\\'"
662   :error "All header lines must be newline terminated")
663
664 (defcustom message-default-headers ""
665   "*A string containing header lines to be inserted in outgoing messages.
666 It is inserted before you edit the message, so you can edit or delete
667 these lines."
668   :group 'message-headers
669   :type 'message-header-lines)
670
671 (defcustom message-default-mail-headers ""
672   "*A string of header lines to be inserted in outgoing mails."
673   :group 'message-headers
674   :group 'message-mail
675   :type 'message-header-lines)
676
677 (defcustom message-default-news-headers ""
678   "*A string of header lines to be inserted in outgoing news
679 articles."
680   :group 'message-headers
681   :group 'message-news
682   :type 'message-header-lines)
683
684 ;; Note: could use /usr/ucb/mail instead of sendmail;
685 ;; options -t, and -v if not interactive.
686 (defcustom message-mailer-swallows-blank-line
687   (if (and (string-match "sparc-sun-sunos\\(\\'\\|[^5]\\)"
688                          system-configuration)
689            (file-readable-p "/etc/sendmail.cf")
690            (let ((buffer (get-buffer-create " *temp*")))
691              (unwind-protect
692                  (save-excursion
693                    (set-buffer buffer)
694                    (insert-file-contents "/etc/sendmail.cf")
695                    (goto-char (point-min))
696                    (let ((case-fold-search nil))
697                      (re-search-forward "^OR\\>" nil t)))
698                (kill-buffer buffer))))
699       ;; According to RFC822, "The field-name must be composed of printable
700       ;; ASCII characters (i. e., characters that have decimal values between
701       ;; 33 and 126, except colon)", i. e., any chars except ctl chars,
702       ;; space, or colon.
703       '(looking-at "[ \t]\\|[][!\"#$%&'()*+,-./0-9;<=>?@A-Z\\\\^_`a-z{|}~]+:"))
704   "*Set this non-nil if the system's mailer runs the header and body together.
705 \(This problem exists on Sunos 4 when sendmail is run in remote mode.)
706 The value should be an expression to test whether the problem will
707 actually occur."
708   :group 'message-sending
709   :type 'sexp)
710
711 ;;; XXX: This symbol is overloaded!  See below.
712 (defvar message-user-agent nil
713   "String of the form of PRODUCT/VERSION.  Used for User-Agent header field.")
714
715 ;; Ignore errors in case this is used in Emacs 19.
716 ;; Don't use ignore-errors because this is copied into loaddefs.el.
717 ;;;###autoload
718 (condition-case nil
719     (define-mail-user-agent 'message-user-agent
720       'message-mail 'message-send-and-exit
721       'message-kill-buffer 'message-send-hook)
722   (error nil))
723
724 (defvar message-mh-deletable-headers '(Message-ID Date Lines Sender)
725   "If non-nil, delete the deletable headers before feeding to mh.")
726
727 (defvar message-send-method-alist
728   '((news message-news-p message-send-via-news)
729     (mail message-mail-p message-send-via-mail))
730   "Alist of ways to send outgoing messages.
731 Each element has the form
732
733   \(TYPE PREDICATE FUNCTION)
734
735 where TYPE is a symbol that names the method; PREDICATE is a function
736 called without any parameters to determine whether the message is
737 a message of type TYPE; and FUNCTION is a function to be called if
738 PREDICATE returns non-nil.  FUNCTION is called with one parameter --
739 the prefix.")
740
741 (defvar message-mail-alias-type 'abbrev
742   "*What alias expansion type to use in Message buffers.
743 The default is `abbrev', which uses mailabbrev.  nil switches
744 mail aliases off.")
745
746 (defcustom message-autosave-directory
747   (nnheader-concat message-directory "drafts/")
748   "*Directory where Message autosaves buffers if Gnus isn't running.
749 If nil, Message won't autosave."
750   :group 'message-buffers
751   :type 'directory)
752
753 ;;; Internal variables.
754 ;;; Well, not really internal.
755
756 (defvar message-mode-syntax-table
757   (let ((table (copy-syntax-table text-mode-syntax-table)))
758     (modify-syntax-entry ?% ". " table)
759     table)
760   "Syntax table used while in Message mode.")
761
762 (defvar message-mode-abbrev-table text-mode-abbrev-table
763   "Abbrev table used in Message mode buffers.
764 Defaults to `text-mode-abbrev-table'.")
765 (defgroup message-headers nil
766   "Message headers."
767   :link '(custom-manual "(message)Variables")
768   :group 'message)
769
770 (defface message-header-to-face
771   '((((class color)
772       (background dark))
773      (:foreground "green2" :bold t))
774     (((class color)
775       (background light))
776      (:foreground "MidnightBlue" :bold t))
777     (t
778      (:bold t :italic t)))
779   "Face used for displaying From headers."
780   :group 'message-faces)
781
782 (defface message-header-cc-face
783   '((((class color)
784       (background dark))
785      (:foreground "green4" :bold t))
786     (((class color)
787       (background light))
788      (:foreground "MidnightBlue"))
789     (t
790      (:bold t)))
791   "Face used for displaying Cc headers."
792   :group 'message-faces)
793
794 (defface message-header-subject-face
795   '((((class color)
796       (background dark))
797      (:foreground "green3"))
798     (((class color)
799       (background light))
800      (:foreground "navy blue" :bold t))
801     (t
802      (:bold t)))
803   "Face used for displaying subject headers."
804   :group 'message-faces)
805
806 (defface message-header-newsgroups-face
807   '((((class color)
808       (background dark))
809      (:foreground "yellow" :bold t :italic t))
810     (((class color)
811       (background light))
812      (:foreground "blue4" :bold t :italic t))
813     (t
814      (:bold t :italic t)))
815   "Face used for displaying newsgroups headers."
816   :group 'message-faces)
817
818 (defface message-header-other-face
819   '((((class color)
820       (background dark))
821      (:foreground "#b00000"))
822     (((class color)
823       (background light))
824      (:foreground "steel blue"))
825     (t
826      (:bold t :italic t)))
827   "Face used for displaying newsgroups headers."
828   :group 'message-faces)
829
830 (defface message-header-name-face
831   '((((class color)
832       (background dark))
833      (:foreground "DarkGreen"))
834     (((class color)
835       (background light))
836      (:foreground "cornflower blue"))
837     (t
838      (:bold t)))
839   "Face used for displaying header names."
840   :group 'message-faces)
841
842 (defface message-header-xheader-face
843   '((((class color)
844       (background dark))
845      (:foreground "blue"))
846     (((class color)
847       (background light))
848      (:foreground "blue"))
849     (t
850      (:bold t)))
851   "Face used for displaying X-Header headers."
852   :group 'message-faces)
853
854 (defface message-separator-face
855   '((((class color)
856       (background dark))
857      (:foreground "blue3"))
858     (((class color)
859       (background light))
860      (:foreground "brown"))
861     (t
862      (:bold t)))
863   "Face used for displaying the separator."
864   :group 'message-faces)
865
866 (defface message-cited-text-face
867   '((((class color)
868       (background dark))
869      (:foreground "red"))
870     (((class color)
871       (background light))
872      (:foreground "red"))
873     (t
874      (:bold t)))
875   "Face used for displaying cited text names."
876   :group 'message-faces)
877
878 (defvar message-font-lock-keywords
879   (let* ((cite-prefix "A-Za-z")
880          (cite-suffix (concat cite-prefix "0-9_.@-"))
881          (content "[ \t]*\\(.+\\(\n[ \t].*\\)*\\)"))
882     `((,(concat "^\\([Tt]o:\\)" content)
883        (1 'message-header-name-face)
884        (2 'message-header-to-face nil t))
885       (,(concat "^\\([GBF]?[Cc][Cc]:\\|[Rr]eply-[Tt]o:\\|"
886                 "[Mm]ail-[Cc]opies-[Tt]o:\\|"
887                 "[Mm]ail-[Rr]eply-[Tt]o:\\|"
888                 "[Mm]ail-[Ff]ollowup-[Tt]o:\\)" content)
889        (1 'message-header-name-face)
890        (2 'message-header-cc-face nil t))
891       (,(concat "^\\([Ss]ubject:\\)" content)
892        (1 'message-header-name-face)
893        (2 'message-header-subject-face nil t))
894       (,(concat "^\\([Nn]ewsgroups:\\|Followup-[Tt]o:\\)" content)
895        (1 'message-header-name-face)
896        (2 'message-header-newsgroups-face nil t))
897       (,(concat "^\\([A-Z][^: \n\t]+:\\)" content)
898        (1 'message-header-name-face)
899        (2 'message-header-other-face nil t))
900       (,(concat "^\\(X-[A-Za-z0-9-]+\\|In-Reply-To\\):" content)
901        (1 'message-header-name-face)
902        (2 'message-header-name-face))
903       ,@(if (and mail-header-separator
904                  (not (equal mail-header-separator "")))
905             `((,(concat "^\\(" (regexp-quote mail-header-separator) "\\)$")
906                1 'message-separator-face))
907           nil)
908       (,(concat "^[ \t]*"
909                 "\\([" cite-prefix "]+[" cite-suffix "]*\\)?"
910                 "[:>|}].*")
911        (0 'message-cited-text-face))))
912   "Additional expressions to highlight in Message mode.")
913
914 ;; XEmacs does it like this.  For Emacs, we have to set the
915 ;; `font-lock-defaults' buffer-local variable.
916 (put 'message-mode 'font-lock-defaults '(message-font-lock-keywords t))
917
918 (defvar message-face-alist
919   '((bold . bold-region)
920     (underline . underline-region)
921     (default . (lambda (b e)
922                  (unbold-region b e)
923                  (ununderline-region b e))))
924   "Alist of mail and news faces for facemenu.
925 The cdr of ech entry is a function for applying the face to a region.")
926
927 (defcustom message-send-hook nil
928   "Hook run before sending messages."
929   :group 'message-various
930   :options '(ispell-message)
931   :type 'hook)
932
933 (defcustom message-send-mail-hook nil
934   "Hook run before sending mail messages."
935   :group 'message-various
936   :type 'hook)
937
938 (defcustom message-send-news-hook nil
939   "Hook run before sending news messages."
940   :group 'message-various
941   :type 'hook)
942
943 (defcustom message-sent-hook nil
944   "Hook run after sending messages."
945   :group 'message-various
946   :type 'hook)
947
948 (defcustom message-use-multi-frames nil
949   "Make new frame when sending messages."
950   :group 'message-frames
951   :type 'boolean)
952
953 (defcustom message-delete-frame-on-exit nil
954   "Delete frame after sending messages."
955   :group 'message-frames
956   :type '(choice (const :tag "off" nil)
957                  (const :tag "always" t)
958                  (const :tag "ask" ask)))
959
960 (defvar message-send-coding-system 'binary
961   "Coding system to encode outgoing mail.")
962
963 ;;; Internal variables.
964
965 (defvar message-buffer-list nil)
966 (defvar message-this-is-news nil)
967 (defvar message-this-is-mail nil)
968 (defvar message-draft-article nil)
969
970 ;; Byte-compiler warning
971 (defvar gnus-active-hashtb)
972 (defvar gnus-read-active-file)
973
974 ;;; Regexp matching the delimiter of messages in UNIX mail format
975 ;;; (UNIX From lines), minus the initial ^.  It should be a copy
976 ;;; of rmail.el's rmail-unix-mail-delimiter.
977 (defvar message-unix-mail-delimiter
978   (let ((time-zone-regexp
979          (concat "\\([A-Z]?[A-Z]?[A-Z][A-Z]\\( DST\\)?"
980                  "\\|[-+]?[0-9][0-9][0-9][0-9]"
981                  "\\|"
982                  "\\) *")))
983     (concat
984      "From "
985
986      ;; Many things can happen to an RFC 822 mailbox before it is put into
987      ;; a `From' line.  The leading phrase can be stripped, e.g.
988      ;; `Joe <@w.x:joe@y.z>' -> `<@w.x:joe@y.z>'.  The <> can be stripped, e.g.
989      ;; `<@x.y:joe@y.z>' -> `@x.y:joe@y.z'.  Everything starting with a CRLF
990      ;; can be removed, e.g.
991      ;;         From: joe@y.z (Joe      K
992      ;;                 User)
993      ;; can yield `From joe@y.z (Joe    K Fri Mar 22 08:11:15 1996', and
994      ;;         From: Joe User
995      ;;                 <joe@y.z>
996      ;; can yield `From Joe User Fri Mar 22 08:11:15 1996'.
997      ;; The mailbox can be removed or be replaced by white space, e.g.
998      ;;         From: "Joe User"{space}{tab}
999      ;;                 <joe@y.z>
1000      ;; can yield `From {space}{tab} Fri Mar 22 08:11:15 1996',
1001      ;; where {space} and {tab} represent the Ascii space and tab characters.
1002      ;; We want to match the results of any of these manglings.
1003      ;; The following regexp rejects names whose first characters are
1004      ;; obviously bogus, but after that anything goes.
1005      "\\([^\0-\b\n-\r\^?].*\\)? "
1006
1007      ;; The time the message was sent.
1008      "\\([^\0-\r \^?]+\\) +"                            ; day of the week
1009      "\\([^\0-\r \^?]+\\) +"                            ; month
1010      "\\([0-3]?[0-9]\\) +"                              ; day of month
1011      "\\([0-2][0-9]:[0-5][0-9]\\(:[0-6][0-9]\\)?\\) *"  ; time of day
1012
1013      ;; Perhaps a time zone, specified by an abbreviation, or by a
1014      ;; numeric offset.
1015      time-zone-regexp
1016
1017      ;; The year.
1018      " \\([0-9][0-9]+\\) *"
1019
1020      ;; On some systems the time zone can appear after the year, too.
1021      time-zone-regexp
1022
1023      ;; Old uucp cruft.
1024      "\\(remote from .*\\)?"
1025
1026      "\n"))
1027   "Regexp matching the delimiter of messages in UNIX mail format.")
1028
1029 (defvar message-unsent-separator
1030   (concat "^ *---+ +Unsent message follows +---+ *$\\|"
1031           "^ *---+ +Returned message +---+ *$\\|"
1032           "^Start of returned message$\\|"
1033           "^ *---+ +Original message +---+ *$\\|"
1034           "^ *--+ +begin message +--+ *$\\|"
1035           "^ *---+ +Original message follows +---+ *$\\|"
1036           "^|? *---+ +Message text follows: +---+ *|?$")
1037   "A regexp that matches the separator before the text of a failed message.")
1038
1039 (defvar message-header-format-alist
1040   `((Newsgroups)
1041     (To . message-fill-address)
1042     (Cc . message-fill-address)
1043     (Subject)
1044     (In-Reply-To)
1045     (Fcc)
1046     (Bcc)
1047     (Date)
1048     (Organization)
1049     (Distribution)
1050     (Lines)
1051     (Expires)
1052     (Message-ID)
1053     ;; (References . message-shorten-references)
1054     (References . message-fill-header)
1055     (User-Agent))
1056   "Alist used for formatting headers.")
1057
1058 (eval-and-compile
1059   (autoload 'message-setup-toolbar "messagexmas")
1060   (autoload 'mh-new-draft-name "mh-comp")
1061   (autoload 'mh-send-letter "mh-comp")
1062   (autoload 'gnus-point-at-eol "gnus-util")
1063   (autoload 'gnus-point-at-bol "gnus-util")
1064   (autoload 'gnus-output-to-mail "gnus-util")
1065   (autoload 'gnus-output-to-rmail "gnus-util")
1066   (autoload 'mail-abbrev-in-expansion-header-p "mailabbrev")
1067   (autoload 'nndraft-request-associate-buffer "nndraft")
1068   (autoload 'nndraft-request-expire-articles "nndraft")
1069   (autoload 'gnus-open-server "gnus-int")
1070   (autoload 'gnus-request-post "gnus-int")
1071   (autoload 'gnus-copy-article-buffer "gnus-msg")
1072   (autoload 'gnus-alive-p "gnus-util")
1073   (autoload 'rmail-output "rmail"))
1074
1075 \f
1076
1077 ;;;
1078 ;;; Utility functions.
1079 ;;;
1080
1081 (defmacro message-y-or-n-p (question show &rest text)
1082   "Ask QUESTION, displaying the rest of the arguments in a temp. buffer if SHOW"
1083   `(message-talkative-question 'y-or-n-p ,question ,show ,@text))
1084
1085 ;; Delete the current line (and the next N lines.);
1086 (defmacro message-delete-line (&optional n)
1087   `(delete-region (progn (beginning-of-line) (point))
1088                   (progn (forward-line ,(or n 1)) (point))))
1089
1090 (defun message-tokenize-header (header &optional separator)
1091   "Split HEADER into a list of header elements.
1092 \",\" is used as the separator."
1093   (if (not header)
1094       nil
1095     (let ((regexp (format "[%s]+" (or separator ",")))
1096           (beg 1)
1097           (first t)
1098           quoted elems paren)
1099       (save-excursion
1100         (message-set-work-buffer)
1101         (insert header)
1102         (goto-char (point-min))
1103         (while (not (eobp))
1104           (if first
1105               (setq first nil)
1106             (forward-char 1))
1107           (cond ((and (> (point) beg)
1108                       (or (eobp)
1109                           (and (looking-at regexp)
1110                                (not quoted)
1111                                (not paren))))
1112                  (push (buffer-substring beg (point)) elems)
1113                  (setq beg (match-end 0)))
1114                 ((= (following-char) ?\")
1115                  (setq quoted (not quoted)))
1116                 ((and (= (following-char) ?\()
1117                       (not quoted))
1118                  (setq paren t))
1119                 ((and (= (following-char) ?\))
1120                       (not quoted))
1121                  (setq paren nil))))
1122         (nreverse elems)))))
1123
1124 (defun message-mail-file-mbox-p (file)
1125   "Say whether FILE looks like a Unix mbox file."
1126   (when (and (file-exists-p file)
1127              (file-readable-p file)
1128              (file-regular-p file))
1129     (nnheader-temp-write nil
1130       (nnheader-insert-file-contents file)
1131       (goto-char (point-min))
1132       (looking-at message-unix-mail-delimiter))))
1133
1134 (defun message-fetch-field (header &optional not-all)
1135   "The same as `mail-fetch-field', only remove all newlines."
1136   (let* ((inhibit-point-motion-hooks t)
1137          (value (mail-fetch-field header nil (not not-all))))
1138     (when value
1139       (nnheader-replace-chars-in-string value ?\n ? ))))
1140
1141 (defun message-add-header (&rest headers)
1142   "Add the HEADERS to the message header, skipping those already present."
1143   (while headers
1144     (let (hclean)
1145       (unless (string-match "^\\([^:]+\\):[ \t]*[^ \t]" (car headers))
1146         (error "Invalid header `%s'" (car headers)))
1147       (setq hclean (match-string 1 (car headers)))
1148     (save-restriction
1149       (message-narrow-to-headers)
1150       (unless (re-search-forward (concat "^" (regexp-quote hclean) ":") nil t)
1151         (insert (car headers) ?\n))))
1152     (setq headers (cdr headers))))
1153
1154 (defun message-fetch-reply-field (header)
1155   "Fetch FIELD from the message we're replying to."
1156   (when (and message-reply-buffer
1157              (buffer-name message-reply-buffer))
1158     (save-excursion
1159       (set-buffer message-reply-buffer)
1160       (message-fetch-field header))))
1161
1162 (defun message-set-work-buffer ()
1163   (if (get-buffer " *message work*")
1164       (progn
1165         (set-buffer " *message work*")
1166         (erase-buffer))
1167     (set-buffer (get-buffer-create " *message work*"))
1168     (kill-all-local-variables)
1169     (buffer-disable-undo (current-buffer))))
1170
1171 (defun message-functionp (form)
1172   "Return non-nil if FORM is funcallable."
1173   (or (and (symbolp form) (fboundp form))
1174       (and (listp form) (eq (car form) 'lambda))
1175       (byte-code-function-p form)))
1176
1177 (defun message-strip-subject-re (subject)
1178   "Remove \"Re:\" from subject lines."
1179   (if (string-match message-subject-re-regexp subject)
1180       (substring subject (match-end 0))
1181     subject))
1182
1183 (defun message-remove-header (header &optional is-regexp first reverse)
1184   "Remove HEADER in the narrowed buffer.
1185 If REGEXP, HEADER is a regular expression.
1186 If FIRST, only remove the first instance of the header.
1187 Return the number of headers removed."
1188   (goto-char (point-min))
1189   (let ((regexp (if is-regexp header (concat "^" (regexp-quote header) ":")))
1190         (number 0)
1191         (case-fold-search t)
1192         last)
1193     (while (and (not (eobp))
1194                 (not last))
1195       (if (if reverse
1196               (not (looking-at regexp))
1197             (looking-at regexp))
1198           (progn
1199             (incf number)
1200             (when first
1201               (setq last t))
1202             (delete-region
1203              (point)
1204              ;; There might be a continuation header, so we have to search
1205              ;; until we find a new non-continuation line.
1206              (progn
1207                (forward-line 1)
1208                (if (re-search-forward "^[^ \t]" nil t)
1209                    (goto-char (match-beginning 0))
1210                  (point-max)))))
1211         (forward-line 1)
1212         (if (re-search-forward "^[^ \t]" nil t)
1213             (goto-char (match-beginning 0))
1214           (point-max))))
1215     number))
1216
1217 (defun message-narrow-to-headers ()
1218   "Narrow the buffer to the head of the message."
1219   (widen)
1220   (narrow-to-region
1221    (goto-char (point-min))
1222    (if (re-search-forward
1223         (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
1224        (match-beginning 0)
1225      (point-max)))
1226   (goto-char (point-min)))
1227
1228 (defun message-narrow-to-head ()
1229   "Narrow the buffer to the head of the message."
1230   (widen)
1231   (narrow-to-region
1232    (goto-char (point-min))
1233    (if (search-forward "\n\n" nil 1)
1234        (1- (point))
1235      (point-max)))
1236   (goto-char (point-min)))
1237
1238 (defun message-news-p ()
1239   "Say whether the current buffer contains a news message."
1240   (and (not message-this-is-mail)
1241        (or message-this-is-news
1242            (save-excursion
1243              (save-restriction
1244                (message-narrow-to-headers)
1245                (and (message-fetch-field "newsgroups")
1246                     (not (message-fetch-field "posted-to"))))))))
1247
1248 (defun message-mail-p ()
1249   "Say whether the current buffer contains a mail message."
1250   (and (not message-this-is-news)
1251        (or message-this-is-mail
1252            (save-excursion
1253              (save-restriction
1254                (message-narrow-to-headers)
1255                (or (message-fetch-field "to")
1256                    (message-fetch-field "cc")
1257                    (message-fetch-field "bcc")))))))
1258
1259 (defun message-next-header ()
1260   "Go to the beginning of the next header."
1261   (beginning-of-line)
1262   (or (eobp) (forward-char 1))
1263   (not (if (re-search-forward "^[^ \t]" nil t)
1264            (beginning-of-line)
1265          (goto-char (point-max)))))
1266
1267 (defun message-sort-headers-1 ()
1268   "Sort the buffer as headers using `message-rank' text props."
1269   (goto-char (point-min))
1270   (sort-subr
1271    nil 'message-next-header
1272    (lambda ()
1273      (message-next-header)
1274      (unless (bobp)
1275        (forward-char -1)))
1276    (lambda ()
1277      (or (get-text-property (point) 'message-rank)
1278          10000))))
1279
1280 (defun message-sort-headers ()
1281   "Sort the headers of the current message according to `message-header-format-alist'."
1282   (interactive)
1283   (save-excursion
1284     (save-restriction
1285       (let ((max (1+ (length message-header-format-alist)))
1286             rank)
1287         (message-narrow-to-headers)
1288         (while (re-search-forward "^[^ \n]+:" nil t)
1289           (put-text-property
1290            (match-beginning 0) (1+ (match-beginning 0))
1291            'message-rank
1292            (if (setq rank (length (memq (assq (intern (buffer-substring
1293                                                        (match-beginning 0)
1294                                                        (1- (match-end 0))))
1295                                               message-header-format-alist)
1296                                         message-header-format-alist)))
1297                (- max rank)
1298              (1+ max)))))
1299       (message-sort-headers-1))))
1300
1301 \f
1302
1303 ;;;
1304 ;;; Message mode
1305 ;;;
1306
1307 ;;; Set up keymap.
1308
1309 (defvar message-mode-map nil)
1310
1311 (unless message-mode-map
1312   (setq message-mode-map (copy-keymap text-mode-map))
1313   (define-key message-mode-map "\C-c?" 'describe-mode)
1314
1315   (define-key message-mode-map "\C-c\C-f\C-t" 'message-goto-to)
1316   (define-key message-mode-map "\C-c\C-f\C-b" 'message-goto-bcc)
1317   (define-key message-mode-map "\C-c\C-f\C-w" 'message-goto-fcc)
1318   (define-key message-mode-map "\C-c\C-f\C-c" 'message-goto-cc)
1319   (define-key message-mode-map "\C-c\C-f\C-s" 'message-goto-subject)
1320   ;; (define-key message-mode-map "\C-c\C-f\C-r" 'message-goto-reply-to)
1321   (define-key message-mode-map "\C-c\C-f\C-r" 'message-goto-mail-reply-to)
1322   (define-key message-mode-map "\C-c\C-f\C-m" 'message-goto-mail-followup-to)
1323   (define-key message-mode-map "\C-c\C-f\C-n" 'message-goto-newsgroups)
1324   (define-key message-mode-map "\C-c\C-f\C-d" 'message-goto-distribution)
1325   (define-key message-mode-map "\C-c\C-f\C-f" 'message-goto-followup-to)
1326   (define-key message-mode-map "\C-c\C-f\C-k" 'message-goto-keywords)
1327   (define-key message-mode-map "\C-c\C-f\C-u" 'message-goto-summary)
1328   (define-key message-mode-map "\C-c\C-b" 'message-goto-body)
1329   (define-key message-mode-map "\C-c\C-i" 'message-goto-signature)
1330
1331   (define-key message-mode-map "\C-c\C-t" 'message-insert-to)
1332   (define-key message-mode-map "\C-c\C-n" 'message-insert-newsgroups)
1333
1334   (define-key message-mode-map "\C-c\C-y" 'message-yank-original)
1335   (define-key message-mode-map "\C-c\C-q" 'message-fill-yanked-message)
1336   (define-key message-mode-map "\C-c\C-w" 'message-insert-signature)
1337   (define-key message-mode-map "\C-c\C-r" 'message-caesar-buffer-body)
1338   (define-key message-mode-map "\C-c\C-o" 'message-sort-headers)
1339   (define-key message-mode-map "\C-c\M-r" 'message-rename-buffer)
1340
1341   (define-key message-mode-map "\C-c\C-c" 'message-send-and-exit)
1342   (define-key message-mode-map "\C-c\C-s" 'message-send)
1343   (define-key message-mode-map "\C-c\C-k" 'message-kill-buffer)
1344   (define-key message-mode-map "\C-c\C-d" 'message-dont-send)
1345
1346   (define-key message-mode-map "\C-c\C-e" 'message-elide-region)
1347   (define-key message-mode-map "\C-c\C-v" 'message-delete-not-region)
1348   (define-key message-mode-map "\C-c\C-z" 'message-kill-to-signature)
1349   (define-key message-mode-map "\M-\r" 'message-newline-and-reformat)
1350
1351   (define-key message-mode-map "\t" 'message-tab))
1352
1353 (easy-menu-define
1354  message-mode-menu message-mode-map "Message Menu."
1355  '("Message"
1356    ["Sort Headers" message-sort-headers t]
1357    ["Yank Original" message-yank-original t]
1358    ["Fill Yanked Message" message-fill-yanked-message t]
1359    ["Insert Signature" message-insert-signature t]
1360    ["Caesar (rot13) Message" message-caesar-buffer-body t]
1361    ["Caesar (rot13) Region" message-caesar-region (mark t)]
1362    ["Elide Region" message-elide-region (mark t)]
1363    ["Delete Outside Region" message-delete-not-region (mark t)]
1364    ["Kill To Signature" message-kill-to-signature t]
1365    ["Newline and Reformat" message-newline-and-reformat t]
1366    ["Rename buffer" message-rename-buffer t]
1367    ["Spellcheck" ispell-message t]
1368    "----"
1369    ["Send Message" message-send-and-exit t]
1370    ["Abort Message" message-dont-send t]
1371    ["Kill Message" message-kill-buffer t]))
1372
1373 (easy-menu-define
1374  message-mode-field-menu message-mode-map ""
1375  '("Field"
1376    ["Fetch To" message-insert-to t]
1377    ["Fetch Newsgroups" message-insert-newsgroups t]
1378    "----"
1379    ["To" message-goto-to t]
1380    ["Subject" message-goto-subject t]
1381    ["Cc" message-goto-cc t]
1382    ["Reply-To" message-goto-reply-to t]
1383    ["Mail-Reply-To" message-goto-mail-reply-to t]
1384    ["Mail-Followup-To" message-goto-mail-followup-to t]
1385    ["Mail-Copies-To" message-goto-mail-copies-to t]
1386    ["Summary" message-goto-summary t]
1387    ["Keywords" message-goto-keywords t]
1388    ["Newsgroups" message-goto-newsgroups t]
1389    ["Followup-To" message-goto-followup-to t]
1390    ["Distribution" message-goto-distribution t]
1391    ["Body" message-goto-body t]
1392    ["Signature" message-goto-signature t]))
1393
1394 (defvar facemenu-add-face-function)
1395 (defvar facemenu-remove-face-function)
1396
1397 ;;;###autoload
1398 (defun message-mode ()
1399   "Major mode for editing mail and news to be sent.
1400 Like Text Mode but with these additional commands:
1401 C-c C-s  message-send (send the message)    C-c C-c  message-send-and-exit
1402 C-c C-f  move to a header field (and create it if there isn't):
1403          C-c C-f C-t  move to To        C-c C-f C-s  move to Subject
1404          C-c C-f C-c  move to Cc        C-c C-f C-b  move to Bcc
1405          C-c C-f C-w  move to Fcc       C-c C-f C-r  move to Reply-To
1406          C-c C-f C-u  move to Summary   C-c C-f C-n  move to Newsgroups
1407          C-c C-f C-k  move to Keywords  C-c C-f C-d  move to Distribution
1408          C-c C-f C-m  move to Mail-Followup-To
1409          C-c C-f C-f  move to Followup-To
1410 C-c C-t  message-insert-to (add a To header to a news followup)
1411 C-c C-n  message-insert-newsgroups (add a Newsgroup header to a news reply)
1412 C-c C-b  message-goto-body (move to beginning of message text).
1413 C-c C-i  message-goto-signature (move to the beginning of the signature).
1414 C-c C-w  message-insert-signature (insert `message-signature-file' file).
1415 C-c C-y  message-yank-original (insert current message, if any).
1416 C-c C-q  message-fill-yanked-message (fill what was yanked).
1417 C-c C-e  message-elide-region (elide the text between point and mark).
1418 C-c C-z  message-kill-to-signature (kill the text up to the signature).
1419 C-c C-r  message-caesar-buffer-body (rot13 the message body)."
1420   (interactive)
1421   (kill-all-local-variables)
1422   (make-local-variable 'message-reply-buffer)
1423   (setq message-reply-buffer nil)
1424   (make-local-variable 'message-send-actions) 
1425   (make-local-variable 'message-exit-actions) 
1426   (make-local-variable 'message-kill-actions)
1427   (make-local-variable 'message-postpone-actions)
1428   (make-local-variable 'message-draft-article)
1429   (make-local-hook 'kill-buffer-hook)
1430   (set-syntax-table message-mode-syntax-table)
1431   (use-local-map message-mode-map)
1432   (setq local-abbrev-table message-mode-abbrev-table)
1433   (setq major-mode 'message-mode)
1434   (setq mode-name "Message")
1435   (setq buffer-offer-save t)
1436   (make-local-variable 'facemenu-add-face-function)
1437   (make-local-variable 'facemenu-remove-face-function)
1438   (setq facemenu-add-face-function
1439         (lambda (face end)
1440           (let ((face-fun (cdr (assq face message-face-alist))))
1441             (if face-fun
1442                 (funcall face-fun (point) end)
1443               (error "Face %s not configured for %s mode" face mode-name)))
1444           "")
1445         facemenu-remove-face-function t)
1446   (make-local-variable 'paragraph-separate)
1447   (make-local-variable 'paragraph-start)
1448   ;; `-- ' precedes the signature.  `-----' appears at the start of the
1449   ;; lines that delimit forwarded messages.
1450   ;; Lines containing just >= 3 dashes, perhaps after whitespace,
1451   ;; are also sometimes used and should be separators.
1452   (setq paragraph-start
1453         (concat (regexp-quote mail-header-separator)
1454                 "$\\|[ \t]*[a-z0-9A-Z]*>+[ \t]*$\\|[ \t]*$\\|"
1455                 "-- $\\|---+$\\|"
1456                 page-delimiter
1457                 ;;!!! Uhm... shurely this can't be right?
1458                 "[> " (regexp-quote message-yank-prefix) "]+$"))
1459   (setq paragraph-separate paragraph-start)
1460   (make-local-variable 'message-reply-headers)
1461   (setq message-reply-headers nil)
1462   (make-local-variable 'message-user-agent)
1463   (make-local-variable 'message-post-method)
1464   (make-local-variable 'message-sent-message-via)
1465   (setq message-sent-message-via nil)
1466   (make-local-variable 'message-checksum)
1467   (setq message-checksum nil)
1468   ;;(when (fboundp 'mail-hist-define-keys)
1469   ;;  (mail-hist-define-keys))
1470   (when (string-match "XEmacs\\|Lucid" emacs-version)
1471     (message-setup-toolbar))
1472   (easy-menu-add message-mode-menu message-mode-map)
1473   (easy-menu-add message-mode-field-menu message-mode-map)
1474   ;; Allow mail alias things.
1475   (when (eq message-mail-alias-type 'abbrev)
1476     (if (fboundp 'mail-abbrevs-setup)
1477         (mail-abbrevs-setup)
1478       (mail-aliases-setup)))
1479   (message-set-auto-save-file-name)
1480   (unless (string-match "XEmacs" emacs-version)
1481     (set (make-local-variable 'font-lock-defaults)
1482          '(message-font-lock-keywords t)))
1483   (make-local-variable 'adaptive-fill-regexp)
1484   (setq adaptive-fill-regexp
1485         (concat "[ \t]*[-a-z0-9A-Z]*>+[ \t]*\\|" adaptive-fill-regexp))
1486   (unless (boundp 'adaptive-fill-first-line-regexp)
1487     (setq adaptive-fill-first-line-regexp nil))
1488   (make-local-variable 'adaptive-fill-first-line-regexp)
1489   (setq adaptive-fill-first-line-regexp
1490         (concat "[ \t]*[-a-z0-9A-Z]*>+[ \t]*\\|"
1491                 adaptive-fill-first-line-regexp))
1492   (run-hooks 'text-mode-hook 'message-mode-hook))
1493
1494 \f
1495
1496 ;;;
1497 ;;; Message mode commands
1498 ;;;
1499
1500 ;;; Movement commands
1501
1502 (defun message-goto-to ()
1503   "Move point to the To header."
1504   (interactive)
1505   (message-position-on-field "To"))
1506
1507 (defun message-goto-subject ()
1508   "Move point to the Subject header."
1509   (interactive)
1510   (message-position-on-field "Subject"))
1511
1512 (defun message-goto-cc ()
1513   "Move point to the Cc header."
1514   (interactive)
1515   (message-position-on-field "Cc" "To"))
1516
1517 (defun message-goto-bcc ()
1518   "Move point to the Bcc  header."
1519   (interactive)
1520   (message-position-on-field "Bcc" "Cc" "To"))
1521
1522 (defun message-goto-fcc ()
1523   "Move point to the Fcc header."
1524   (interactive)
1525   (message-position-on-field "Fcc" "To" "Newsgroups"))
1526
1527 (defun message-goto-reply-to ()
1528   "Move point to the Reply-To header."
1529   (interactive)
1530   (message-position-on-field "Reply-To" "Subject"))
1531
1532 (defun message-goto-mail-reply-to ()
1533   "Move point to the Mail-Reply-To header."
1534   (interactive)
1535   (message-position-on-field "Mail-Reply-To" "Subject"))
1536
1537 (defun message-goto-mail-followup-to ()
1538   "Move point to the Mail-Followup-To header."
1539   (interactive)
1540   (message-position-on-field "Mail-Followup-To" "Subject"))
1541
1542 (defun message-goto-mail-copies-to ()
1543   "Move point to the Mail-Copies-To header."
1544   (interactive)
1545   (message-position-on-field "Mail-Copies-To" "Subject"))
1546
1547 (defun message-goto-newsgroups ()
1548   "Move point to the Newsgroups header."
1549   (interactive)
1550   (message-position-on-field "Newsgroups"))
1551
1552 (defun message-goto-distribution ()
1553   "Move point to the Distribution header."
1554   (interactive)
1555   (message-position-on-field "Distribution"))
1556
1557 (defun message-goto-followup-to ()
1558   "Move point to the Followup-To header."
1559   (interactive)
1560   (message-position-on-field "Followup-To" "Newsgroups"))
1561
1562 (defun message-goto-keywords ()
1563   "Move point to the Keywords header."
1564   (interactive)
1565   (message-position-on-field "Keywords" "Subject"))
1566
1567 (defun message-goto-summary ()
1568   "Move point to the Summary header."
1569   (interactive)
1570   (message-position-on-field "Summary" "Subject"))
1571
1572 (defun message-goto-body ()
1573   "Move point to the beginning of the message body."
1574   (interactive)
1575   (if (looking-at "[ \t]*\n") (expand-abbrev))
1576   (goto-char (point-min))
1577   (search-forward (concat "\n" mail-header-separator "\n") nil t))
1578
1579 (defun message-goto-eoh ()
1580   "Move point to the end of the headers."
1581   (interactive)
1582   (message-goto-body)
1583   (forward-line -2))
1584
1585 (defun message-goto-signature ()
1586   "Move point to the beginning of the message signature.
1587 If there is no signature in the article, go to the end and
1588 return nil."
1589   (interactive)
1590   (goto-char (point-min))
1591   (if (re-search-forward message-signature-separator nil t)
1592       (forward-line 1)
1593     (goto-char (point-max))
1594     nil))
1595
1596 \f
1597
1598 (defun message-insert-to (&optional force)
1599   "Insert a To header that points to the author of the article being replied to.
1600 If the original author requested not to be sent mail, the function signals
1601 an error.
1602 With the prefix argument FORCE, insert the header anyway."
1603   (interactive "P")
1604   (let ((co (message-fetch-reply-field "mail-copies-to")))
1605     (when (and (null force)
1606                co
1607                (equal (downcase co) "never"))
1608       (error "The user has requested not to have copies sent via mail")))
1609   (when (and (message-position-on-field "To")
1610              (mail-fetch-field "to")
1611              (not (string-match "\\` *\\'" (mail-fetch-field "to"))))
1612     (insert ", "))
1613   (insert (or (message-fetch-reply-field "reply-to")
1614               (message-fetch-reply-field "from") "")))
1615
1616 (defun message-insert-newsgroups ()
1617   "Insert the Newsgroups header from the article being replied to."
1618   (interactive)
1619   (when (and (message-position-on-field "Newsgroups")
1620              (mail-fetch-field "newsgroups")
1621              (not (string-match "\\` *\\'" (mail-fetch-field "newsgroups"))))
1622     (insert ","))
1623   (insert (or (message-fetch-reply-field "newsgroups") "")))
1624
1625 \f
1626
1627 ;;; Various commands
1628
1629 (defun message-delete-not-region (beg end)
1630   "Delete everything in the body of the current message that is outside of the region."
1631   (interactive "r")
1632   (save-excursion
1633     (goto-char end)
1634     (delete-region (point) (if (not (message-goto-signature))
1635                                (point)
1636                              (forward-line -2)
1637                              (point)))
1638     (insert "\n")
1639     (goto-char beg)
1640     (delete-region beg (progn (message-goto-body)
1641                               (forward-line 2)
1642                               (point))))
1643   (when (message-goto-signature)
1644     (forward-line -2)))
1645
1646 (defun message-kill-to-signature ()
1647   "Deletes all text up to the signature."
1648   (interactive)
1649   (let ((point (point)))
1650     (message-goto-signature)
1651     (unless (eobp)
1652       (forward-line -2))
1653     (kill-region point (point))
1654     (unless (bolp)
1655       (insert "\n"))))
1656
1657 (defun message-newline-and-reformat ()
1658   "Insert four newlines, and then reformat if inside quoted text."
1659   (interactive)
1660   (let ((point (point))
1661         quoted)
1662     (save-excursion
1663       (beginning-of-line)
1664       (setq quoted (looking-at (regexp-quote message-yank-prefix))))
1665     (insert "\n\n\n\n")
1666     (when quoted
1667       (insert message-yank-prefix))
1668     (fill-paragraph nil)
1669     (goto-char point)
1670     (forward-line 2)))
1671
1672 (defun message-insert-signature (&optional force)
1673   "Insert a signature.  See documentation for the `message-signature' variable."
1674   (interactive (list 0))
1675   (let* ((signature
1676           (cond
1677            ((and (null message-signature)
1678                  (eq force 0))
1679             (save-excursion
1680               (goto-char (point-max))
1681               (not (re-search-backward
1682                     message-signature-separator nil t))))
1683            ((and (null message-signature)
1684                  force)
1685             t)
1686            ((message-functionp message-signature)
1687             (funcall message-signature))
1688            ((listp message-signature)
1689             (eval message-signature))
1690            (t message-signature)))
1691          (signature
1692           (cond ((stringp signature)
1693                  signature)
1694                 ((and (eq t signature)
1695                       message-signature-file
1696                       (file-exists-p message-signature-file))
1697                  signature))))
1698     (when signature
1699       (goto-char (point-max))
1700       ;; Insert the signature.
1701       (unless (bolp)
1702         (insert "\n"))
1703       (insert "\n-- \n")
1704       (if (eq signature t)
1705           (insert-file-contents message-signature-file)
1706         (insert signature))
1707       (goto-char (point-max))
1708       (or (bolp) (insert "\n")))))
1709
1710 (defun message-elide-region (b e)
1711   "Elide the text between point and mark.
1712 An ellipsis (from `message-elide-elipsis') will be inserted where the
1713 text was killed."
1714   (interactive "r")
1715   (kill-region b e)
1716   (unless (bolp)
1717     (insert "\n"))
1718   (insert message-elide-elipsis))
1719
1720 (defvar message-caesar-translation-table nil)
1721
1722 (defun message-caesar-region (b e &optional n)
1723   "Caesar rotation of region by N, default 13, for decrypting netnews."
1724   (interactive
1725    (list
1726     (min (point) (or (mark t) (point)))
1727     (max (point) (or (mark t) (point)))
1728     (when current-prefix-arg
1729       (prefix-numeric-value current-prefix-arg))))
1730
1731   (setq n (if (numberp n) (mod n 26) 13)) ;canonize N
1732   (unless (or (zerop n)                 ; no action needed for a rot of 0
1733               (= b e))                  ; no region to rotate
1734     ;; We build the table, if necessary.
1735     (when (or (not message-caesar-translation-table)
1736               (/= (aref message-caesar-translation-table ?a) (+ ?a n)))
1737         (setq message-caesar-translation-table
1738               (message-make-caesar-translation-table n)))
1739     ;; Then we translate the region.  Do it this way to retain
1740     ;; text properties.
1741     (while (< b e)
1742       (subst-char-in-region
1743        b (1+ b) (char-after b)
1744        (aref message-caesar-translation-table (char-after b)))
1745       (incf b))))
1746
1747 (defun message-make-caesar-translation-table (n)
1748   "Create a rot table with offset N."
1749   (let ((i -1)
1750         (table (make-string 256 0)))
1751     (while (< (incf i) 256)
1752       (aset table i i))
1753     (concat
1754      (substring table 0 ?A)
1755      (substring table (+ ?A n) (+ ?A n (- 26 n)))
1756      (substring table ?A (+ ?A n))
1757      (substring table (+ ?A 26) ?a)
1758      (substring table (+ ?a n) (+ ?a n (- 26 n)))
1759      (substring table ?a (+ ?a n))
1760      (substring table (+ ?a 26) 255))))
1761
1762 (defun message-caesar-buffer-body (&optional rotnum)
1763   "Caesar rotates all letters in the current buffer by 13 places.
1764 Used to encode/decode possiblyun offensive messages (commonly in net.jokes).
1765 With prefix arg, specifies the number of places to rotate each letter forward.
1766 Mail and USENET news headers are not rotated."
1767   (interactive (if current-prefix-arg
1768                    (list (prefix-numeric-value current-prefix-arg))
1769                  (list nil)))
1770   (save-excursion
1771     (save-restriction
1772       (when (message-goto-body)
1773         (narrow-to-region (point) (point-max)))
1774       (message-caesar-region (point-min) (point-max) rotnum))))
1775
1776 (defun message-pipe-buffer-body (program)
1777   "Pipe the message body in the current buffer through PROGRAM."
1778   (save-excursion
1779     (save-restriction
1780       (when (message-goto-body)
1781         (narrow-to-region (point) (point-max)))
1782       (let ((body (buffer-substring (point-min) (point-max))))
1783         (unless (equal 0 (call-process-region
1784                            (point-min) (point-max) program t t))
1785             (insert body)
1786             (message "%s failed." program))))))
1787
1788 (defun message-rename-buffer (&optional enter-string)
1789   "Rename the *message* buffer to \"*message* RECIPIENT\".
1790 If the function is run with a prefix, it will ask for a new buffer
1791 name, rather than giving an automatic name."
1792   (interactive "Pbuffer name: ")
1793   (save-excursion
1794     (save-restriction
1795       (goto-char (point-min))
1796       (narrow-to-region (point)
1797                         (search-forward mail-header-separator nil 'end))
1798       (let* ((mail-to (or
1799                        (if (message-news-p) (message-fetch-field "Newsgroups")
1800                          (message-fetch-field "To"))
1801                        ""))
1802              (mail-trimmed-to
1803               (if (string-match "," mail-to)
1804                   (concat (substring mail-to 0 (match-beginning 0)) ", ...")
1805                 mail-to))
1806              (name-default (concat "*message* " mail-trimmed-to))
1807              (name (if enter-string
1808                        (read-string "New buffer name: " name-default)
1809                      name-default)))
1810         (rename-buffer name t)))))
1811
1812 (defun message-fill-yanked-message (&optional justifyp)
1813   "Fill the paragraphs of a message yanked into this one.
1814 Numeric argument means justify as well."
1815   (interactive "P")
1816   (save-excursion
1817     (goto-char (point-min))
1818     (search-forward (concat "\n" mail-header-separator "\n") nil t)
1819     (let ((fill-prefix message-yank-prefix))
1820       (fill-individual-paragraphs (point) (point-max) justifyp t))))
1821
1822 (defun message-indent-citation ()
1823   "Modify text just inserted from a message to be cited.
1824 The inserted text should be the region.
1825 When this function returns, the region is again around the modified text.
1826
1827 Normally, indent each nonblank line `message-indentation-spaces' spaces.
1828 However, if `message-yank-prefix' is non-nil, insert that prefix on each line."
1829   (let ((start (point)))
1830     ;; Remove unwanted headers.
1831     (when message-ignored-cited-headers
1832       (let (all-removed)
1833         (save-restriction
1834           (narrow-to-region
1835            (goto-char start)
1836            (if (search-forward "\n\n" nil t)
1837                (1- (point))
1838              (point)))
1839           (message-remove-header message-ignored-cited-headers t)
1840           (when (= (point-min) (point-max))
1841             (setq all-removed t))
1842           (goto-char (point-max)))
1843         (if all-removed
1844             (goto-char start)
1845           (forward-line 1))))
1846     ;; Delete blank lines at the start of the buffer.
1847     (while (and (point-min)
1848                 (eolp)
1849                 (not (eobp)))
1850       (message-delete-line))
1851     ;; Delete blank lines at the end of the buffer.
1852     (goto-char (point-max))
1853     (unless (eolp)
1854       (insert "\n"))
1855     (while (and (zerop (forward-line -1))
1856                 (looking-at "$"))
1857       (message-delete-line))
1858     ;; Do the indentation.
1859     (if (null message-yank-prefix)
1860         (indent-rigidly start (mark t) message-indentation-spaces)
1861       (save-excursion
1862         (goto-char start)
1863         (while (< (point) (mark t))
1864           (insert message-yank-prefix)
1865           (forward-line 1))))
1866     (goto-char start)))
1867
1868 (defvar gnus-article-copy)
1869 (defun message-yank-original (&optional arg)
1870   "Insert the message being replied to, if any.
1871 Puts point before the text and mark after.
1872 Normally indents each nonblank line ARG spaces (default 3).  However,
1873 if `message-yank-prefix' is non-nil, insert that prefix on each line.
1874
1875 This function uses `message-cite-function' to do the actual citing.
1876
1877 Just \\[universal-argument] as argument means don't indent, insert no
1878 prefix, and don't delete any headers."
1879   (interactive "P")
1880   (let ((modified (buffer-modified-p)))
1881     (when (and message-reply-buffer
1882                message-cite-function)
1883       (gnus-copy-article-buffer)
1884       (setq message-reply-buffer gnus-article-copy)
1885       (delete-windows-on message-reply-buffer t)
1886       (insert-buffer message-reply-buffer)
1887       (funcall message-cite-function)
1888       (message-exchange-point-and-mark)
1889       (unless (bolp)
1890         (insert ?\n))
1891       (unless modified
1892         (setq message-checksum (message-checksum))))))
1893
1894 (defun message-cite-original-without-signature ()
1895   "Cite function in the standard Message manner."
1896   (let ((start (point))
1897         (end (mark t))
1898         (functions
1899          (when message-indent-citation-function
1900            (if (listp message-indent-citation-function)
1901                message-indent-citation-function
1902              (list message-indent-citation-function)))))
1903     (goto-char end)
1904     (when (re-search-backward "^-- $" start t)
1905       ;; Also peel off any blank lines before the signature.
1906       (forward-line -1)
1907       (while (looking-at "^[ \t]*$")
1908         (forward-line -1))
1909       (forward-line 1)
1910       (delete-region (point) end))
1911     (goto-char start)
1912     (while functions
1913       (funcall (pop functions)))
1914     (when message-citation-line-function
1915       (unless (bolp)
1916         (insert "\n"))
1917       (funcall message-citation-line-function))))
1918
1919 (defun message-cite-original ()
1920   "Cite function in the standard Message manner."
1921   (if (and (boundp 'mail-citation-hook)
1922            mail-citation-hook)
1923       (run-hooks 'mail-citation-hook)
1924     (let ((start (point))
1925           (functions
1926            (when message-indent-citation-function
1927              (if (listp message-indent-citation-function)
1928                  message-indent-citation-function
1929                (list message-indent-citation-function)))))
1930       (goto-char start)
1931       (while functions
1932         (funcall (pop functions)))
1933       (when message-citation-line-function
1934         (unless (bolp)
1935           (insert "\n"))
1936         (funcall message-citation-line-function)))))
1937
1938 (defun message-insert-citation-line ()
1939   "Function that inserts a simple citation line."
1940   (when message-reply-headers
1941     (insert (mail-header-from message-reply-headers) " writes:\n\n")))
1942
1943 (defun message-position-on-field (header &rest afters)
1944   (let ((case-fold-search t))
1945     (save-restriction
1946       (narrow-to-region
1947        (goto-char (point-min))
1948        (progn
1949          (re-search-forward
1950           (concat "^" (regexp-quote mail-header-separator) "$"))
1951          (match-beginning 0)))
1952       (goto-char (point-min))
1953       (if (re-search-forward (concat "^" (regexp-quote header) ":") nil t)
1954           (progn
1955             (re-search-forward "^[^ \t]" nil 'move)
1956             (beginning-of-line)
1957             (skip-chars-backward "\n")
1958             t)
1959         (while (and afters
1960                     (not (re-search-forward
1961                           (concat "^" (regexp-quote (car afters)) ":")
1962                           nil t)))
1963           (pop afters))
1964         (when afters
1965           (re-search-forward "^[^ \t]" nil 'move)
1966           (beginning-of-line))
1967         (insert header ": \n")
1968         (forward-char -1)
1969         nil))))
1970
1971 (defun message-remove-signature ()
1972   "Remove the signature from the text between point and mark.
1973 The text will also be indented the normal way."
1974   (save-excursion
1975     (let ((start (point))
1976           mark)
1977       (if (not (re-search-forward message-signature-separator (mark t) t))
1978           ;; No signature here, so we just indent the cited text.
1979           (message-indent-citation)
1980         ;; Find the last non-empty line.
1981         (forward-line -1)
1982         (while (looking-at "[ \t]*$")
1983           (forward-line -1))
1984         (forward-line 1)
1985         (setq mark (set-marker (make-marker) (point)))
1986         (goto-char start)
1987         (message-indent-citation)
1988         ;; Enable undoing the deletion.
1989         (undo-boundary)
1990         (delete-region mark (mark t))
1991         (set-marker mark nil)))))
1992
1993 \f
1994
1995 ;;;
1996 ;;; Sending messages
1997 ;;;
1998
1999 ;; Avoid byte-compile warning.
2000 (defvar message-encoding-buffer nil)
2001 (defvar message-edit-buffer nil)
2002 (defvar message-mime-mode nil)
2003
2004 (defun message-send-and-exit (&optional arg)
2005   "Send message like `message-send', then, if no errors, exit from mail buffer."
2006   (interactive "P")
2007   (let ((buf (current-buffer))
2008         (actions message-exit-actions)
2009         (frame (selected-frame))
2010         (org-frame message-original-frame))
2011     (when (and (message-send arg)
2012                (buffer-name buf))
2013       (if message-kill-buffer-on-exit
2014           (kill-buffer buf)
2015         (bury-buffer buf)
2016         (when (eq buf (current-buffer))
2017           (message-bury buf)))
2018       (message-do-actions actions)
2019       (message-delete-frame frame org-frame))))
2020
2021 (defun message-dont-send ()
2022   "Don't send the message you have been editing."
2023   (interactive)
2024   (set-buffer-modified-p t)
2025   (save-buffer)
2026   (let ((actions message-postpone-actions))
2027     (message-bury (current-buffer))
2028     (message-do-actions actions)))
2029
2030 (defun message-kill-buffer ()
2031   "Kill the current buffer."
2032   (interactive)
2033   (when (or (not (buffer-modified-p))
2034             (yes-or-no-p "Message modified; kill anyway? "))
2035     (let ((actions message-kill-actions)
2036           (frame (selected-frame))
2037           (org-frame message-original-frame))
2038       (setq buffer-file-name nil)
2039       (kill-buffer (current-buffer))
2040       (message-do-actions actions)
2041       (message-delete-frame frame org-frame))))
2042
2043 (defun message-delete-frame (frame org-frame)
2044   "Delete frame for editing message."
2045   (when (and (or (and (featurep 'xemacs)
2046                       (not (eq 'tty (device-type))))
2047                  window-system
2048                  (>= emacs-major-version 20))
2049              (or (and (eq message-delete-frame-on-exit t)
2050                       (select-frame frame)
2051                       (or (eq frame org-frame)
2052                           (prog1
2053                               (y-or-n-p "Delete this frame?")
2054                             (message ""))))
2055                  (and (eq message-delete-frame-on-exit 'ask)
2056                       (select-frame frame)
2057                       (prog1
2058                           (y-or-n-p "Delete this frame?")
2059                         (message "")))))
2060     (delete-frame frame)))
2061
2062 (defun message-bury (buffer)
2063   "Bury this mail buffer."
2064   (let ((newbuf (other-buffer buffer)))
2065     (bury-buffer buffer)
2066     (if (and (fboundp 'frame-parameters)
2067              (cdr (assq 'dedicated (frame-parameters)))
2068              (not (null (delq (selected-frame) (visible-frame-list)))))
2069         (delete-frame (selected-frame))
2070       (switch-to-buffer newbuf))))
2071
2072 (defun message-send (&optional arg)
2073   "Send the message in the current buffer.
2074 If `message-interactive' is non-nil, wait for success indication
2075 or error messages, and inform user.
2076 Otherwise any failure is reported in a message back to
2077 the user from the mailer."
2078   (interactive "P")
2079   ;; Disabled test.
2080   (when (or (buffer-modified-p)
2081             (message-check-element 'unchanged)
2082             (y-or-n-p "No changes in the buffer; really send? "))
2083     ;; Make it possible to undo the coming changes.
2084     (undo-boundary)
2085     (let ((inhibit-read-only t))
2086       (put-text-property (point-min) (point-max) 'read-only nil))
2087     (message-fix-before-sending)
2088     (run-hooks 'message-send-hook)
2089     (message "Sending...")
2090     (let ((message-encoding-buffer
2091            (message-generate-new-buffer-clone-locals " message encoding"))
2092           (message-edit-buffer (current-buffer))
2093           (message-mime-mode mime-edit-mode-flag)
2094           (alist message-send-method-alist)
2095           (success t)
2096           elem sent)
2097       (save-excursion
2098         (set-buffer message-encoding-buffer)
2099         (erase-buffer)
2100         (insert-buffer message-edit-buffer)
2101         (funcall message-encode-function)
2102         (while (and success
2103                     (setq elem (pop alist)))
2104           (when (and (or (not (funcall (cadr elem)))
2105                          (and (or (not (memq (car elem)
2106                                              message-sent-message-via))
2107                                   (y-or-n-p
2108                                    (format
2109                                     "Already sent message via %s; resend? "
2110                                     (car elem))))
2111                               (setq success (funcall (caddr elem) arg)))))
2112             (setq sent t))))
2113       (when (and success sent)
2114         (message-do-fcc)
2115         ;;(when (fboundp 'mail-hist-put-headers-into-history)
2116         ;; (mail-hist-put-headers-into-history))
2117         (run-hooks 'message-sent-hook)
2118         (message "Sending...done")
2119         ;; Mark the buffer as unmodified and delete autosave.
2120         (set-buffer-modified-p nil)
2121         (delete-auto-save-file-if-necessary t)
2122         (message-disassociate-draft)
2123         ;; Delete other mail buffers and stuff.
2124         (message-do-send-housekeeping)
2125         (message-do-actions message-send-actions)
2126         ;; Return success.
2127         t))))
2128
2129 (defun message-send-via-mail (arg)
2130   "Send the current message via mail."
2131   (message-send-mail arg))
2132
2133 (defun message-send-via-news (arg)
2134   "Send the current message via news."
2135   (message-send-news arg))
2136
2137 (defun message-fix-before-sending ()
2138   "Do various things to make the message nice before sending it."
2139   ;; Make sure there's a newline at the end of the message.
2140   (goto-char (point-max))
2141   (unless (bolp)
2142     (insert "\n"))
2143   ;; Delete all invisible text.
2144   (when (text-property-any (point-min) (point-max) 'invisible t)
2145     (put-text-property (point-min) (point-max) 'invisible nil)
2146     (unless (yes-or-no-p "Invisible text found and made visible; continue posting?")
2147       (error "Invisible text found and made visible"))))
2148
2149 (defun message-add-action (action &rest types)
2150   "Add ACTION to be performed when doing an exit of type TYPES."
2151   (let (var)
2152     (while types
2153       (set (setq var (intern (format "message-%s-actions" (pop types))))
2154            (nconc (symbol-value var) (list action))))))
2155
2156 (defun message-do-actions (actions)
2157   "Perform all actions in ACTIONS."
2158   ;; Now perform actions on successful sending.
2159   (while actions
2160     (ignore-errors
2161       (cond
2162        ;; A simple function.
2163        ((message-functionp (car actions))
2164         (funcall (car actions)))
2165        ;; Something to be evaled.
2166        (t
2167         (eval (car actions)))))
2168     (pop actions)))
2169
2170 (defun message-send-mail (&optional arg)
2171   (require 'mail-utils)
2172   (let ((tembuf (message-generate-new-buffer-clone-locals " message temp"))
2173         (case-fold-search nil)
2174         (news (message-news-p)))
2175     (save-restriction
2176       (message-narrow-to-headers)
2177       ;; Insert some headers.
2178       (let ((message-deletable-headers
2179              (if news nil message-deletable-headers)))
2180         (message-generate-headers message-required-mail-headers))
2181       ;; Let the user do all of the above.
2182       (run-hooks 'message-header-hook))
2183     (unwind-protect
2184         (save-excursion
2185           (set-buffer tembuf)
2186           (erase-buffer)
2187           (insert-buffer message-encoding-buffer)
2188           ;; Remove some headers.
2189           (save-restriction
2190             (message-narrow-to-headers)
2191             ;; Remove some headers.
2192             (message-remove-header message-ignored-mail-headers t))
2193           (goto-char (point-max))
2194           ;; require one newline at the end.
2195           (or (= (preceding-char) ?\n)
2196               (insert ?\n))
2197           (when (and news
2198                      (or (message-fetch-field "cc")
2199                          (message-fetch-field "to")))
2200             (message-insert-courtesy-copy))
2201           (mime-edit-maybe-split-and-send
2202            (function
2203             (lambda ()
2204               (interactive)
2205               (funcall message-send-mail-function)
2206               )))
2207           (funcall message-send-mail-function))
2208       (kill-buffer tembuf))
2209     (set-buffer message-edit-buffer)
2210     (push 'mail message-sent-message-via)))
2211
2212 (defun message-send-mail-with-sendmail ()
2213   "Send off the prepared buffer with sendmail."
2214   (let ((errbuf (if message-interactive
2215                     (generate-new-buffer " sendmail errors")
2216                   0))
2217         resend-addresses delimline)
2218     (let ((case-fold-search t))
2219       (save-restriction
2220         (message-narrow-to-headers)
2221         ;; XXX: We need to handle Resent-CC/Resent-BCC, too.
2222         (setq resend-addresses (message-fetch-field "resent-to")))
2223       ;; Change header-delimiter to be what sendmail expects.
2224       (goto-char (point-min))
2225       (re-search-forward
2226        (concat "^" (regexp-quote mail-header-separator) "\n"))
2227       (replace-match "\n")
2228       (backward-char 1)
2229       (setq delimline (point-marker))
2230       (run-hooks 'message-send-mail-hook)
2231       ;; Insert an extra newline if we need it to work around
2232       ;; Sun's bug that swallows newlines.
2233       (goto-char (1+ delimline))
2234       (when (eval message-mailer-swallows-blank-line)
2235         (newline))
2236       (when message-interactive
2237         (save-excursion
2238           (set-buffer errbuf)
2239           (erase-buffer))))
2240     (let ((default-directory "/")
2241           (coding-system-for-write message-send-coding-system))
2242       (apply 'call-process-region
2243              (append (list (point-min) (point-max)
2244                            (if (boundp 'sendmail-program)
2245                                sendmail-program
2246                              "/usr/lib/sendmail")
2247                            nil errbuf nil "-oi")
2248                      ;; Always specify who from,
2249                      ;; since some systems have broken sendmails.
2250                      ;; But some systems are more broken with -f, so
2251                      ;; we'll let users override this.
2252                      (if (null message-sendmail-f-is-evil)
2253                          (list "-f" (user-login-name)))
2254                      ;; These mean "report errors by mail"
2255                      ;; and "deliver in background".
2256                      (if (null message-interactive) '("-oem" "-odb"))
2257                      ;; Get the addresses from the message
2258                      ;; unless this is a resend.
2259                      ;; We must not do that for a resend
2260                      ;; because we would find the original addresses.
2261                      ;; For a resend, include the specific addresses.
2262                      (if resend-addresses
2263                          (list resend-addresses)
2264                        '("-t")))))
2265     (when message-interactive
2266       (save-excursion
2267         (set-buffer errbuf)
2268         (goto-char (point-min))
2269         (while (re-search-forward "\n\n* *" nil t)
2270           (replace-match "; "))
2271         (if (not (zerop (buffer-size)))
2272             (error "Sending...failed to %s"
2273                    (buffer-substring (point-min) (point-max)))))
2274       (when (bufferp errbuf)
2275         (kill-buffer errbuf)))))
2276
2277 (defun message-send-mail-with-qmail ()
2278   "Pass the prepared message buffer to qmail-inject.
2279 Refer to the documentation for the variable `message-send-mail-function'
2280 to find out how to use this."
2281   ;; replace the header delimiter with a blank line.
2282   (goto-char (point-min))
2283   (re-search-forward
2284    (concat "^" (regexp-quote mail-header-separator) "\n"))
2285   (replace-match "\n")
2286   (backward-char 1)
2287   (run-hooks 'message-send-mail-hook)
2288   ;; send the message
2289   (case
2290       (let ((coding-system-for-write message-send-coding-system))
2291         (apply
2292          'call-process-region 1 (point-max) message-qmail-inject-program
2293          nil nil nil
2294          ;; qmail-inject's default behaviour is to look for addresses on the
2295          ;; command line; if there're none, it scans the headers.
2296          ;; yes, it does The Right Thing w.r.t. Resent-To and it's kin.
2297          ;;
2298          ;; in general, ALL of qmail-inject's defaults are perfect for simply
2299          ;; reading a formatted (i. e., at least a To: or Resent-To header)
2300          ;; message from stdin.
2301          ;;
2302          ;; qmail also has the advantage of not having been raped by
2303          ;; various vendors, so we don't have to allow for that, either --
2304          ;; compare this with message-send-mail-with-sendmail and weep
2305          ;; for sendmail's lost innocence.
2306          ;;
2307          ;; all this is way cool coz it lets us keep the arguments entirely
2308          ;; free for -inject-arguments -- a big win for the user and for us
2309          ;; since we don't have to play that double-guessing game and the user
2310          ;; gets full control (no gestapo'ish -f's, for instance).  --sj
2311          message-qmail-inject-args))
2312     ;; qmail-inject doesn't say anything on it's stdout/stderr,
2313     ;; we have to look at the retval instead
2314     (0 nil)
2315     (1   (error "qmail-inject reported permanent failure"))
2316     (111 (error "qmail-inject reported transient failure"))
2317     ;; should never happen
2318     (t   (error "qmail-inject reported unknown failure"))))
2319
2320 (defun message-send-mail-with-mh ()
2321   "Send the prepared message buffer with mh."
2322   (let ((mh-previous-window-config nil)
2323         (name (mh-new-draft-name)))
2324     (setq buffer-file-name name)
2325     ;; MH wants to generate these headers itself.
2326     (when message-mh-deletable-headers
2327       (let ((headers message-mh-deletable-headers))
2328         (while headers
2329           (goto-char (point-min))
2330           (and (re-search-forward
2331                 (concat "^" (symbol-name (car headers)) ": *") nil t)
2332                (message-delete-line))
2333           (pop headers))))
2334     (run-hooks 'message-send-mail-hook)
2335     ;; Pass it on to mh.
2336     (mh-send-letter)))
2337
2338 (defun message-send-mail-with-smtp ()
2339   "Send off the prepared buffer with SMTP."
2340   (require 'smtp) ; XXX
2341   (let ((case-fold-search t)
2342         recipients)
2343     (save-restriction
2344       (message-narrow-to-headers)
2345       (setq recipients
2346             ;; XXX: Should be replaced by better one.
2347             (smtp-deduce-address-list (current-buffer)
2348                                       (point-min) (point-max)))
2349       ;; Remove BCC lines.
2350       (message-remove-header "bcc"))
2351     ;; replace the header delimiter with a blank line.
2352     (goto-char (point-min))
2353     (re-search-forward
2354      (concat "^" (regexp-quote mail-header-separator) "\n"))
2355     (replace-match "\n")
2356     (backward-char 1)
2357     (run-hooks 'message-send-mail-hook)
2358     (if recipients
2359         (let ((result (smtp-via-smtp user-mail-address
2360                                      recipients
2361                                      (current-buffer))))
2362           (unless (eq result t)
2363             (error "Sending failed; " result)))
2364       (error "Sending failed; no recipients"))))
2365
2366 (defun message-send-news (&optional arg)
2367   (let ((tembuf (message-generate-new-buffer-clone-locals " *message temp*"))
2368         (case-fold-search nil)
2369         (method (if (message-functionp message-post-method)
2370                     (funcall message-post-method arg)
2371                   message-post-method))
2372         (message-syntax-checks
2373          (if arg
2374              (cons '(existing-newsgroups . disabled)
2375                    message-syntax-checks)
2376            message-syntax-checks))
2377         result)
2378     (save-restriction
2379       (message-narrow-to-headers)
2380       ;; Insert some headers.
2381       (message-generate-headers message-required-news-headers)
2382       ;; Let the user do all of the above.
2383       (run-hooks 'message-header-hook))
2384     (message-cleanup-headers)
2385     (if (not (message-check-news-syntax))
2386         (progn
2387           ;;(message "Posting not performed")
2388           nil)
2389       (unwind-protect
2390           (save-excursion
2391             (set-buffer tembuf)
2392             (buffer-disable-undo (current-buffer))
2393             (erase-buffer)
2394             (insert-buffer message-encoding-buffer)
2395             ;; Remove some headers.
2396             (save-restriction
2397               (message-narrow-to-headers)
2398               ;; Remove some headers.
2399               (message-remove-header message-ignored-news-headers t))
2400             (goto-char (point-max))
2401             ;; require one newline at the end.
2402             (or (= (preceding-char) ?\n)
2403                 (insert ?\n))
2404             (mime-edit-maybe-split-and-send
2405              (function
2406               (lambda ()
2407                 (interactive)
2408                 (save-restriction
2409                   (std11-narrow-to-header mail-header-separator)
2410                   (goto-char (point-min))
2411                   (when (re-search-forward "^Message-Id:" nil t)
2412                     (delete-region (match-end 0)(std11-field-end))
2413                     (insert (concat " " (message-make-message-id)))
2414                     ))
2415                 (funcall message-send-news-function method)
2416                 )))
2417             (setq result (funcall message-send-news-function method)))
2418         (kill-buffer tembuf))
2419       (set-buffer message-edit-buffer)
2420       (if result
2421           (push 'news message-sent-message-via)
2422         (message "Couldn't send message via news: %s"
2423                  (nnheader-get-report (car method)))
2424         nil))))
2425
2426 ;; 1997-09-29 by MORIOKA Tomohiko
2427 (defun message-send-news-with-gnus (method)
2428   (let ((case-fold-search t))
2429     ;; Remove the delimiter.
2430     (goto-char (point-min))
2431     (re-search-forward
2432      (concat "^" (regexp-quote mail-header-separator) "\n"))
2433     (replace-match "\n")
2434     (backward-char 1)
2435     (run-hooks 'message-send-news-hook)
2436     ;;(require (car method))
2437     ;;(funcall (intern (format "%s-open-server" (car method)))
2438     ;;(cadr method) (cddr method))
2439     ;;(setq result
2440     ;;    (funcall (intern (format "%s-request-post" (car method)))
2441     ;;             (cadr method)))
2442     (gnus-open-server method)
2443     (gnus-request-post method)
2444     ))
2445
2446 ;;;
2447 ;;; Header generation & syntax checking.
2448 ;;;
2449
2450 (defmacro message-check (type &rest forms)
2451   "Eval FORMS if TYPE is to be checked."
2452   `(or (message-check-element ,type)
2453        (save-excursion
2454          ,@forms)))
2455
2456 (put 'message-check 'lisp-indent-function 1)
2457 (put 'message-check 'edebug-form-spec '(form body))
2458
2459 (defun message-check-element (type)
2460   "Returns non-nil if this type is not to be checked."
2461   (if (eq message-syntax-checks 'dont-check-for-anything-just-trust-me)
2462       t
2463     (let ((able (assq type message-syntax-checks)))
2464       (and (consp able)
2465            (eq (cdr able) 'disabled)))))
2466
2467 (defun message-check-news-syntax ()
2468   "Check the syntax of the message."
2469   (save-excursion
2470     (save-restriction
2471       (widen)
2472       (and
2473        ;; We narrow to the headers and check them first.
2474        (save-excursion
2475          (save-restriction
2476            (message-narrow-to-headers)
2477            (message-check-news-header-syntax)))
2478        ;; Check the body.
2479        (save-excursion
2480          (set-buffer message-edit-buffer)
2481          (message-check-news-body-syntax))))))
2482
2483 (defun message-check-news-header-syntax ()
2484   (and
2485    ;; Check the Subject header.
2486    (message-check 'subject
2487      (let* ((case-fold-search t)
2488             (subject (message-fetch-field "subject")))
2489        (or
2490         (and subject
2491              (not (string-match "\\`[ \t]*\\'" subject)))
2492         (ignore
2493          (message
2494           "The subject field is empty or missing.  Posting is denied.")))))
2495    ;; Check for commands in Subject.
2496    (message-check 'subject-cmsg
2497      (if (string-match "^cmsg " (message-fetch-field "subject"))
2498          (y-or-n-p
2499           "The control code \"cmsg\" is in the subject.  Really post? ")
2500        t))
2501    ;; Check for multiple identical headers.
2502    (message-check 'multiple-headers
2503      (let (found)
2504        (while (and (not found)
2505                    (re-search-forward "^[^ \t:]+: " nil t))
2506          (save-excursion
2507            (or (re-search-forward
2508                 (concat "^"
2509                         (regexp-quote
2510                          (setq found
2511                                (buffer-substring
2512                                 (match-beginning 0) (- (match-end 0) 2))))
2513                         ":")
2514                 nil t)
2515                (setq found nil))))
2516        (if found
2517            (y-or-n-p (format "Multiple %s headers.  Really post? " found))
2518          t)))
2519    ;; Check for Version and Sendsys.
2520    (message-check 'sendsys
2521      (if (re-search-forward "^Sendsys:\\|^Version:" nil t)
2522          (y-or-n-p
2523           (format "The article contains a %s command.  Really post? "
2524                   (buffer-substring (match-beginning 0)
2525                                     (1- (match-end 0)))))
2526        t))
2527    ;; See whether we can shorten Followup-To.
2528    (message-check 'shorten-followup-to
2529      (let ((newsgroups (message-fetch-field "newsgroups"))
2530            (followup-to (message-fetch-field "followup-to"))
2531            to)
2532        (when (and newsgroups
2533                   (string-match "," newsgroups)
2534                   (not followup-to)
2535                   (not
2536                    (zerop
2537                     (length
2538                      (setq to (completing-read
2539                                "Followups to: (default all groups) "
2540                                (mapcar (lambda (g) (list g))
2541                                        (cons "poster"
2542                                              (message-tokenize-header
2543                                               newsgroups)))))))))
2544          (goto-char (point-min))
2545          (insert "Followup-To: " to "\n"))
2546        t))
2547    ;; Check "Shoot me".
2548    (message-check 'shoot
2549      (if (re-search-forward
2550           "Message-ID.*.i-did-not-set--mail-host-address--so-shoot-me" nil t)
2551          (y-or-n-p "You appear to have a misconfigured system.  Really post? ")
2552        t))
2553    ;; Check for Approved.
2554    (message-check 'approved
2555      (if (re-search-forward "^Approved:" nil t)
2556          (y-or-n-p "The article contains an Approved header.  Really post? ")
2557        t))
2558    ;; Check the Message-ID header.
2559    (message-check 'message-id
2560      (let* ((case-fold-search t)
2561             (message-id (message-fetch-field "message-id" t)))
2562        (or (not message-id)
2563            ;; Is there an @ in the ID?
2564            (and (string-match "@" message-id)
2565                 ;; Is there a dot in the ID?
2566                 (string-match "@[^.]*\\." message-id)
2567                 ;; Does the ID end with a dot?
2568                 (not (string-match "\\.>" message-id)))
2569            (y-or-n-p
2570             (format "The Message-ID looks strange: \"%s\".  Really post? "
2571                     message-id)))))
2572    ;; Check the Newsgroups & Followup-To headers.
2573    (message-check 'existing-newsgroups
2574      (let* ((case-fold-search t)
2575             (newsgroups (message-fetch-field "newsgroups"))
2576             (followup-to (message-fetch-field "followup-to"))
2577             (groups (message-tokenize-header
2578                      (if followup-to
2579                          (concat newsgroups "," followup-to)
2580                        newsgroups)))
2581             (hashtb (and (boundp 'gnus-active-hashtb)
2582                          gnus-active-hashtb))
2583             errors)
2584        (if (or (not hashtb)
2585                (not (boundp 'gnus-read-active-file))
2586                (not gnus-read-active-file)
2587                (eq gnus-read-active-file 'some))
2588            t
2589          (while groups
2590            (when (and (not (boundp (intern (car groups) hashtb)))
2591                       (not (equal (car groups) "poster")))
2592              (push (car groups) errors))
2593            (pop groups))
2594          (if (not errors)
2595              t
2596            (y-or-n-p
2597             (format
2598              "Really post to %s unknown group%s: %s "
2599              (if (= (length errors) 1) "this" "these")
2600              (if (= (length errors) 1) "" "s")
2601              (mapconcat 'identity errors ", ")))))))
2602    ;; Check the Newsgroups & Followup-To headers for syntax errors.
2603    (message-check 'valid-newsgroups
2604      (let ((case-fold-search t)
2605            (headers '("Newsgroups" "Followup-To"))
2606            header error)
2607        (while (and headers (not error))
2608          (when (setq header (mail-fetch-field (car headers)))
2609            (if (or
2610                 (not
2611                  (string-match
2612                   "\\`\\([-+_&.a-zA-Z0-9]+\\)?\\(,[-+_&.a-zA-Z0-9]+\\)*\\'"
2613                   header))
2614                 (memq
2615                  nil (mapcar
2616                       (lambda (g)
2617                         (not (string-match "\\.\\'\\|\\.\\." g)))
2618                       (message-tokenize-header header ","))))
2619                (setq error t)))
2620          (unless error
2621            (pop headers)))
2622        (if (not error)
2623            t
2624          (y-or-n-p
2625           (format "The %s header looks odd: \"%s\".  Really post? "
2626                   (car headers) header)))))
2627    (message-check 'repeated-newsgroups
2628      (let ((case-fold-search t)
2629            (headers '("Newsgroups" "Followup-To"))
2630            header error groups group)
2631        (while (and headers
2632                    (not error))
2633          (when (setq header (mail-fetch-field (pop headers)))
2634            (setq groups (message-tokenize-header header ","))
2635            (while (setq group (pop groups))
2636              (when (member group groups)
2637                (setq error group
2638                      groups nil)))))
2639        (if (not error)
2640            t
2641          (y-or-n-p
2642           (format "Group %s is repeated in headers.  Really post? " error)))))
2643    ;; Check the From header.
2644    (message-check 'from
2645      (let* ((case-fold-search t)
2646             (from (message-fetch-field "from"))
2647             (ad (nth 1 (std11-extract-address-components from))))
2648        (cond
2649         ((not from)
2650          (message "There is no From line.  Posting is denied.")
2651          nil)
2652         ((or (not (string-match "@[^\\.]*\\." ad)) ;larsi@ifi
2653              (string-match "\\.\\." ad) ;larsi@ifi..uio
2654              (string-match "@\\." ad)   ;larsi@.ifi.uio
2655              (string-match "\\.$" ad)   ;larsi@ifi.uio.
2656              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
2657              (string-match "(.*).*(.*)" from)) ;(lars) (lars)
2658          (message
2659           "Denied posting -- the From looks strange: \"%s\"." from)
2660          nil)
2661         (t t))))))
2662
2663 (defun message-check-news-body-syntax ()
2664   (and
2665    ;; Check for long lines.
2666    (message-check 'long-lines
2667      (goto-char (point-min))
2668      (re-search-forward
2669       (concat "^" (regexp-quote mail-header-separator) "$"))
2670      (while (and
2671              (progn
2672                (end-of-line)
2673                (< (current-column) 80))
2674              (zerop (forward-line 1))))
2675      (or (bolp)
2676          (eobp)
2677          (y-or-n-p
2678           "You have lines longer than 79 characters.  Really post? ")))
2679    ;; Check whether the article is empty.
2680    (message-check 'empty
2681      (goto-char (point-min))
2682      (re-search-forward
2683       (concat "^" (regexp-quote mail-header-separator) "$"))
2684      (forward-line 1)
2685      (let ((b (point)))
2686        (goto-char (point-max))
2687        (re-search-backward message-signature-separator nil t)
2688        (beginning-of-line)
2689        (or (re-search-backward "[^ \n\t]" b t)
2690            (y-or-n-p "Empty article.  Really post? "))))
2691    ;; Check for control characters.
2692    (message-check 'control-chars
2693      (if (re-search-forward "[\000-\007\013\015-\037\200-\237]" nil t)
2694          (y-or-n-p
2695           "The article contains control characters.  Really post? ")
2696        t))
2697    ;; Check excessive size.
2698    (message-check 'size
2699      (if (> (buffer-size) 60000)
2700          (y-or-n-p
2701           (format "The article is %d octets long.  Really post? "
2702                   (buffer-size)))
2703        t))
2704    ;; Check whether any new text has been added.
2705    (message-check 'new-text
2706      (or
2707       (not message-checksum)
2708       (not (eq (message-checksum) message-checksum))
2709       (y-or-n-p
2710        "It looks like no new text has been added.  Really post? ")))
2711    ;; Check the length of the signature.
2712    (message-check 'signature
2713      (goto-char (point-max))
2714      (if (or (not (re-search-backward message-signature-separator nil t))
2715              (search-forward message-forward-end-separator nil t))
2716          t
2717        (if (> (count-lines (point) (point-max)) 5)
2718            (y-or-n-p
2719             (format
2720              "Your .sig is %d lines; it should be max 4.  Really post? "
2721              (1- (count-lines (point) (point-max)))))
2722          t)))))
2723
2724 (defun message-checksum ()
2725   "Return a \"checksum\" for the current buffer."
2726   (let ((sum 0))
2727     (save-excursion
2728       (goto-char (point-min))
2729       (re-search-forward
2730        (concat "^" (regexp-quote mail-header-separator) "$"))
2731       (while (not (eobp))
2732         (when (not (looking-at "[ \t\n]"))
2733           (setq sum (logxor (ash sum 1) (if (natnump sum) 0 1)
2734                             (following-char))))
2735         (forward-char 1)))
2736     sum))
2737
2738 (defun message-do-fcc ()
2739   "Process Fcc headers in the current buffer."
2740   (let ((case-fold-search t)
2741         (coding-system-for-write 'raw-text)
2742         list file)
2743     (save-excursion
2744       (set-buffer (get-buffer-create " *message temp*"))
2745       (buffer-disable-undo (current-buffer))
2746       (erase-buffer)
2747       (insert-buffer-substring message-encoding-buffer)
2748       (save-restriction
2749         (message-narrow-to-headers)
2750         (while (setq file (message-fetch-field "fcc"))
2751           (push file list)
2752           (message-remove-header "fcc" nil t)))
2753       (run-hooks 'message-header-hook 'message-before-do-fcc-hook)
2754       (goto-char (point-min))
2755       (re-search-forward (concat "^" (regexp-quote mail-header-separator) "$"))
2756       (replace-match "" t t)
2757       ;; Process FCC operations.
2758       (while list
2759         (setq file (pop list))
2760         (if (string-match "^[ \t]*|[ \t]*\\(.*\\)[ \t]*$" file)
2761             ;; Pipe the article to the program in question.
2762             (call-process-region (point-min) (point-max) shell-file-name
2763                                  nil nil nil shell-command-switch
2764                                  (match-string 1 file))
2765           ;; Save the article.
2766           (setq file (expand-file-name file))
2767           (unless (file-exists-p (file-name-directory file))
2768             (make-directory (file-name-directory file) t))
2769           (if (and message-fcc-handler-function
2770                    (not (eq message-fcc-handler-function 'rmail-output)))
2771               (funcall message-fcc-handler-function file)
2772             (if (and (file-readable-p file) (mail-file-babyl-p file))
2773                 (rmail-output file 1 nil t)
2774               (let ((mail-use-rfc822 t))
2775                 (rmail-output file 1 t t))))))
2776
2777       (kill-buffer (current-buffer)))))
2778
2779 (defun message-output (filename)
2780   "Append this article to Unix/babyl mail file.."
2781   (if (and (file-readable-p filename)
2782            (mail-file-babyl-p filename))
2783       (gnus-output-to-rmail filename t)
2784     (gnus-output-to-mail filename t)))
2785
2786 (defun message-cleanup-headers ()
2787   "Do various automatic cleanups of the headers."
2788   ;; Remove empty lines in the header.
2789   (save-restriction
2790     (message-narrow-to-headers)
2791     ;; Remove blank lines.
2792     (while (re-search-forward "^[ \t]*\n" nil t)
2793       (replace-match "" t t))
2794
2795     ;; Correct Newsgroups and Followup-To headers:  Change sequence of
2796     ;; spaces to comma and eliminate spaces around commas.  Eliminate
2797     ;; embedded line breaks.
2798     (goto-char (point-min))
2799     (while (re-search-forward "^\\(Newsgroups\\|Followup-To\\): +" nil t)
2800       (save-restriction
2801         (narrow-to-region
2802          (point)
2803          (if (re-search-forward "^[^ \t]" nil t)
2804              (match-beginning 0)
2805            (forward-line 1)
2806            (point)))
2807         (goto-char (point-min))
2808         (while (re-search-forward "\n[ \t]+" nil t)
2809           (replace-match " " t t))      ;No line breaks (too confusing)
2810         (goto-char (point-min))
2811         (while (re-search-forward "[ \t\n]*,[ \t\n]*\\|[ \t]+" nil t)
2812           (replace-match "," t t))
2813         (goto-char (point-min))
2814         ;; Remove trailing commas.
2815         (when (re-search-forward ",+$" nil t)
2816           (replace-match "" t t))))))
2817
2818 (defun message-make-date ()
2819   "Make a valid data header."
2820   (let ((now (current-time)))
2821     (timezone-make-date-arpa-standard
2822      (current-time-string now) (current-time-zone now))))
2823
2824 (defun message-make-followup-subject (subject)
2825   "Make a followup Subject."
2826   (cond
2827    ((and (eq message-use-subject-re 'guess)
2828          (string-match message-subject-encoded-re-regexp subject))
2829     subject)
2830    (message-use-subject-re
2831     (concat "Re: " (message-strip-subject-re subject)))
2832    (t subject)))
2833
2834 (defun message-make-message-id ()
2835   "Make a unique Message-ID."
2836   (concat "<" (message-unique-id)
2837           (let ((psubject (save-excursion (message-fetch-field "subject")))
2838                 (psupersedes
2839                  (save-excursion (message-fetch-field "supersedes"))))
2840             (if (or
2841                  (and message-reply-headers
2842                       (mail-header-references message-reply-headers)
2843                       (mail-header-subject message-reply-headers)
2844                       psubject
2845                       (mail-header-subject message-reply-headers)
2846                       (not (string=
2847                             (message-strip-subject-re
2848                              (mail-header-subject message-reply-headers))
2849                             (message-strip-subject-re psubject))))
2850                  (and psupersedes
2851                       (string-match "_-_@" psupersedes)))
2852                 "_-_" ""))
2853           "@" (message-make-fqdn) ">"))
2854
2855 (defvar message-unique-id-char nil)
2856
2857 ;; If you ever change this function, make sure the new version
2858 ;; cannot generate IDs that the old version could.
2859 ;; You might for example insert a "." somewhere (not next to another dot
2860 ;; or string boundary), or modify the "fsf" string.
2861 (defun message-unique-id ()
2862   ;; Don't use microseconds from (current-time), they may be unsupported.
2863   ;; Instead we use this randomly inited counter.
2864   (setq message-unique-id-char
2865         (% (1+ (or message-unique-id-char (logand (random t) (1- (lsh 1 20)))))
2866            ;; (current-time) returns 16-bit ints,
2867            ;; and 2^16*25 just fits into 4 digits i base 36.
2868            (* 25 25)))
2869   (let ((tm (current-time)))
2870     (concat
2871      (if (memq system-type '(ms-dos emx vax-vms))
2872          (let ((user (downcase (user-login-name))))
2873            (while (string-match "[^a-z0-9_]" user)
2874              (aset user (match-beginning 0) ?_))
2875            user)
2876        (message-number-base36 (user-uid) -1))
2877      (message-number-base36 (+ (car   tm)
2878                                (lsh (% message-unique-id-char 25) 16)) 4)
2879      (message-number-base36 (+ (nth 1 tm)
2880                                (lsh (/ message-unique-id-char 25) 16)) 4)
2881      ;; Append the newsreader name, because while the generated
2882      ;; ID is unique to this newsreader, other newsreaders might
2883      ;; otherwise generate the same ID via another algorithm.
2884      ".fsf")))
2885
2886 (defun message-number-base36 (num len)
2887   (if (if (< len 0)
2888           (<= num 0)
2889         (= len 0))
2890       ""
2891     (concat (message-number-base36 (/ num 36) (1- len))
2892             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
2893                                   (% num 36))))))
2894
2895 (defun message-make-organization ()
2896   "Make an Organization header."
2897   (let* ((organization
2898           (when message-user-organization
2899                 (if (message-functionp message-user-organization)
2900                     (funcall message-user-organization)
2901                   message-user-organization))))
2902     (save-excursion
2903       (message-set-work-buffer)
2904       (cond ((stringp organization)
2905              (insert organization))
2906             ((and (eq t organization)
2907                   message-user-organization-file
2908                   (file-exists-p message-user-organization-file))
2909              (insert-file-contents message-user-organization-file)))
2910       (goto-char (point-min))
2911       (while (re-search-forward "[\t\n]+" nil t)
2912         (replace-match "" t t))
2913       (unless (zerop (buffer-size))
2914         (buffer-string)))))
2915
2916 (defun message-make-lines ()
2917   "Count the number of lines and return numeric string."
2918   (save-excursion
2919     (save-restriction
2920       (widen)
2921       (goto-char (point-min))
2922       (re-search-forward
2923        (concat "^" (regexp-quote mail-header-separator) "$"))
2924       (forward-line 1)
2925       (int-to-string (count-lines (point) (point-max))))))
2926
2927 (defun message-make-in-reply-to ()
2928   "Return the In-Reply-To header for this message."
2929   (when message-reply-headers
2930     (let ((mid (mail-header-message-id message-reply-headers))
2931           (from (mail-header-from message-reply-headers))
2932           (date (mail-header-date message-reply-headers)))
2933       (when mid
2934         (concat mid
2935                 (when from
2936                   (let ((stop-pos 
2937                          (string-match "  *at \\|  *@ \\| *(\\| *<" from)))
2938                     (concat "\n ("
2939                             (if stop-pos (substring from 0 stop-pos) from)
2940                             "'s message of " 
2941                             (if (or (not date) (string= date ""))
2942                                 "(unknown date)" date)
2943                             ")"))))))))
2944
2945 (defun message-make-distribution ()
2946   "Make a Distribution header."
2947   (let ((orig-distribution (message-fetch-reply-field "distribution")))
2948     (cond ((message-functionp message-distribution-function)
2949            (funcall message-distribution-function))
2950           (t orig-distribution))))
2951
2952 (defun message-make-expires ()
2953   "Return an Expires header based on `message-expires'."
2954   (let ((current (current-time))
2955         (future (* 1.0 message-expires 60 60 24)))
2956     ;; Add the future to current.
2957     (setcar current (+ (car current) (round (/ future (expt 2 16)))))
2958     (setcar (cdr current) (+ (nth 1 current) (% (round future) (expt 2 16))))
2959     ;; Return the date in the future in UT.
2960     (timezone-make-date-arpa-standard
2961      (current-time-string current) (current-time-zone current) '(0 "UT"))))
2962
2963 (defun message-make-path ()
2964   "Return uucp path."
2965   (let ((login-name (user-login-name)))
2966     (cond ((null message-user-path)
2967            (concat (system-name) "!" login-name))
2968           ((stringp message-user-path)
2969            ;; Support GENERICPATH.  Suggested by vixie@decwrl.dec.com.
2970            (concat message-user-path "!" login-name))
2971           (t login-name))))
2972
2973 (defun message-make-from ()
2974   "Make a From header."
2975   (let* ((style message-from-style)
2976          (login (message-make-address))
2977          (fullname
2978           (or (and (boundp 'user-full-name)
2979                    user-full-name)
2980               (user-full-name))))
2981     (when (string= fullname "&")
2982       (setq fullname (user-login-name)))
2983     (save-excursion
2984       (message-set-work-buffer)
2985       (cond
2986        ((or (null style)
2987             (equal fullname ""))
2988         (insert login))
2989        ((or (eq style 'angles)
2990             (and (not (eq style 'parens))
2991                  ;; Use angles if no quoting is needed, or if parens would
2992                  ;; need quoting too.
2993                  (or (not (string-match "[^- !#-'*+/-9=?A-Z^-~]" fullname))
2994                      (let ((tmp (concat fullname nil)))
2995                        (while (string-match "([^()]*)" tmp)
2996                          (aset tmp (match-beginning 0) ?-)
2997                          (aset tmp (1- (match-end 0)) ?-))
2998                        (string-match "[\\()]" tmp)))))
2999         (insert fullname)
3000         (goto-char (point-min))
3001         ;; Look for a character that cannot appear unquoted
3002         ;; according to RFC 822.
3003         (when (re-search-forward "[^- !#-'*+/-9=?A-Z^-~]" nil 1)
3004           ;; Quote fullname, escaping specials.
3005           (goto-char (point-min))
3006           (insert "\"")
3007           (while (re-search-forward "[\"\\]" nil 1)
3008             (replace-match "\\\\\\&" t))
3009           (insert "\""))
3010         (insert " <" login ">"))
3011        (t                               ; 'parens or default
3012         (insert login " (")
3013         (let ((fullname-start (point)))
3014           (insert fullname)
3015           (goto-char fullname-start)
3016           ;; RFC 822 says \ and nonmatching parentheses
3017           ;; must be escaped in comments.
3018           ;; Escape every instance of ()\ ...
3019           (while (re-search-forward "[()\\]" nil 1)
3020             (replace-match "\\\\\\&" t))
3021           ;; ... then undo escaping of matching parentheses,
3022           ;; including matching nested parentheses.
3023           (goto-char fullname-start)
3024           (while (re-search-forward
3025                   "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
3026                   nil 1)
3027             (replace-match "\\1(\\3)" t)
3028             (goto-char fullname-start)))
3029         (insert ")")))
3030       (buffer-string))))
3031
3032 (defun message-make-sender ()
3033   "Return the \"real\" user address.
3034 This function tries to ignore all user modifications, and
3035 give as trustworthy answer as possible."
3036   (concat (user-login-name) "@" (system-name)))
3037
3038 (defun message-make-address ()
3039   "Make the address of the user."
3040   (or (message-user-mail-address)
3041       (concat (user-login-name) "@" (message-make-domain))))
3042
3043 (defun message-user-mail-address ()
3044   "Return the pertinent part of `user-mail-address'."
3045   (when user-mail-address
3046     (if (string-match " " user-mail-address)
3047         (nth 1 (std11-extract-address-components user-mail-address))
3048       user-mail-address)))
3049
3050 (defun message-make-fqdn ()
3051   "Return user's fully qualified domain name."
3052   (let ((system-name (system-name))
3053         (user-mail (message-user-mail-address)))
3054     (cond
3055      ((string-match "[^.]\\.[^.]" system-name)
3056       ;; `system-name' returned the right result.
3057       system-name)
3058      ;; Try `mail-host-address'.
3059      ((and (boundp 'mail-host-address)
3060            (stringp mail-host-address)
3061            (string-match "\\." mail-host-address))
3062       mail-host-address)
3063      ;; We try `user-mail-address' as a backup.
3064      ((and user-mail
3065            (string-match "\\." user-mail)
3066            (string-match "@\\(.*\\)\\'" user-mail))
3067       (match-string 1 user-mail))
3068      ;; Default to this bogus thing.
3069      (t
3070       (concat system-name ".i-did-not-set--mail-host-address--so-shoot-me")))))
3071
3072 (defun message-make-host-name ()
3073   "Return the name of the host."
3074   (let ((fqdn (message-make-fqdn)))
3075     (string-match "^[^.]+\\." fqdn)
3076     (substring fqdn 0 (1- (match-end 0)))))
3077
3078 (defun message-make-domain ()
3079   "Return the domain name."
3080   (or mail-host-address
3081       (message-make-fqdn)))
3082
3083 (defun message-generate-headers (headers)
3084   "Prepare article HEADERS.
3085 Headers already prepared in the buffer are not modified."
3086   (save-restriction
3087     (message-narrow-to-headers)
3088     (let* ((Date (message-make-date))
3089            (Message-ID (message-make-message-id))
3090            (Organization (message-make-organization))
3091            (From (message-make-from))
3092            (Path (message-make-path))
3093            (Subject nil)
3094            (Newsgroups nil)
3095            (In-Reply-To (message-make-in-reply-to))
3096            (To nil)
3097            (Distribution (message-make-distribution))
3098            (Lines (message-make-lines))
3099            (User-Agent message-user-agent)
3100            (Expires (message-make-expires))
3101            (case-fold-search t)
3102            header value elem)
3103       ;; First we remove any old generated headers.
3104       (let ((headers message-deletable-headers))
3105         (unless (buffer-modified-p)
3106           (setq headers (delq 'Message-ID (copy-sequence headers))))
3107         (while headers
3108           (goto-char (point-min))
3109           (and (re-search-forward
3110                 (concat "^" (symbol-name (car headers)) ": *") nil t)
3111                (get-text-property (1+ (match-beginning 0)) 'message-deletable)
3112                (message-delete-line))
3113           (pop headers)))
3114       ;; Go through all the required headers and see if they are in the
3115       ;; articles already.  If they are not, or are empty, they are
3116       ;; inserted automatically - except for Subject, Newsgroups and
3117       ;; Distribution.
3118       (while headers
3119         (goto-char (point-min))
3120         (setq elem (pop headers))
3121         (if (consp elem)
3122             (if (eq (car elem) 'optional)
3123                 (setq header (cdr elem))
3124               (setq header (car elem)))
3125           (setq header elem))
3126         (when (or (not (re-search-forward
3127                         (concat "^"
3128                                 (regexp-quote
3129                                  (downcase
3130                                   (if (stringp header)
3131                                       header
3132                                     (symbol-name header))))
3133                                 ":")
3134                         nil t))
3135                   (progn
3136                     ;; The header was found.  We insert a space after the
3137                     ;; colon, if there is none.
3138                     (if (/= (following-char) ? ) (insert " ") (forward-char 1))
3139                     ;; Find out whether the header is empty...
3140                     (looking-at "[ \t]*$")))
3141           ;; So we find out what value we should insert.
3142           (setq value
3143                 (cond
3144                  ((and (consp elem) (eq (car elem) 'optional))
3145                   ;; This is an optional header.  If the cdr of this
3146                   ;; is something that is nil, then we do not insert
3147                   ;; this header.
3148                   (setq header (cdr elem))
3149                   (or (and (fboundp (cdr elem)) (funcall (cdr elem)))
3150                       (and (boundp (cdr elem)) (symbol-value (cdr elem)))))
3151                  ((consp elem)
3152                   ;; The element is a cons.  Either the cdr is a
3153                   ;; string to be inserted verbatim, or it is a
3154                   ;; function, and we insert the value returned from
3155                   ;; this function.
3156                   (or (and (stringp (cdr elem)) (cdr elem))
3157                       (and (fboundp (cdr elem)) (funcall (cdr elem)))))
3158                  ((and (boundp header) (symbol-value header))
3159                   ;; The element is a symbol.  We insert the value
3160                   ;; of this symbol, if any.
3161                   (symbol-value header))
3162                  (t
3163                   ;; We couldn't generate a value for this header,
3164                   ;; so we just ask the user.
3165                   (read-from-minibuffer
3166                    (format "Empty header for %s; enter value: " header)))))
3167           ;; Finally insert the header.
3168           (when (and value
3169                      (not (equal value "")))
3170             (save-excursion
3171               (if (bolp)
3172                   (progn
3173                     ;; This header didn't exist, so we insert it.
3174                     (goto-char (point-max))
3175                     (insert (if (stringp header) header (symbol-name header))
3176                             ": " value "\n")
3177                     (forward-line -1))
3178                 ;; The value of this header was empty, so we clear
3179                 ;; totally and insert the new value.
3180                 (delete-region (point) (gnus-point-at-eol))
3181                 (insert value))
3182               ;; Add the deletable property to the headers that require it.
3183               (and (memq header message-deletable-headers)
3184                    (progn (beginning-of-line) (looking-at "[^:]+: "))
3185                    (add-text-properties
3186                     (point) (match-end 0)
3187                     '(message-deletable t face italic) (current-buffer)))))))
3188       ;; Insert new Sender if the From is strange.
3189       (let ((from (message-fetch-field "from"))
3190             (sender (message-fetch-field "sender"))
3191             (secure-sender (message-make-sender)))
3192         (when (and from
3193                    (not (message-check-element 'sender))
3194                    (not (string=
3195                          (downcase
3196                           (cadr (std11-extract-address-components from)))
3197                          (downcase secure-sender)))
3198                    (or (null sender)
3199                        (not
3200                         (string=
3201                          (downcase
3202                           (cadr (std11-extract-address-components sender)))
3203                          (downcase secure-sender)))))
3204           (goto-char (point-min))
3205           ;; Rename any old Sender headers to Original-Sender.
3206           (when (re-search-forward "^\\(Original-\\)*Sender:" nil t)
3207             (beginning-of-line)
3208             (insert "Original-")
3209             (beginning-of-line))
3210           (when (or (message-news-p)
3211                     (string-match "@.+\\.." secure-sender))
3212             (insert "Sender: " secure-sender "\n")))))))
3213
3214 (defun message-insert-courtesy-copy ()
3215   "Insert a courtesy message in mail copies of combined messages."
3216   (let (newsgroups)
3217     (save-excursion
3218       (save-restriction
3219         (message-narrow-to-headers)
3220         (when (setq newsgroups (message-fetch-field "newsgroups"))
3221           (goto-char (point-max))
3222           (insert "Posted-To: " newsgroups "\n")))
3223       (forward-line 1)
3224       (when message-courtesy-message
3225         (cond
3226          ((string-match "%s" message-courtesy-message)
3227           (insert (format message-courtesy-message newsgroups)))
3228          (t
3229           (insert message-courtesy-message)))))))
3230
3231 ;;;
3232 ;;; Setting up a message buffer
3233 ;;;
3234
3235 (defun message-fill-address (header value)
3236   (save-restriction
3237     (narrow-to-region (point) (point))
3238     (insert (capitalize (symbol-name header))
3239             ": "
3240             (if (consp value) (car value) value)
3241             "\n")
3242     (narrow-to-region (point-min) (1- (point-max)))
3243     (let (quoted last)
3244       (goto-char (point-min))
3245       (while (not (eobp))
3246         (skip-chars-forward "^,\"" (point-max))
3247         (if (or (= (following-char) ?,)
3248                 (eobp))
3249             (when (not quoted)
3250               (if last
3251                   (save-excursion
3252                     (goto-char last)
3253                     (looking-at "[ \t]*")
3254                     (replace-match "\n " t t)))
3255               (setq last (1+ (point))))
3256           (setq quoted (not quoted)))
3257         (unless (eobp)
3258           (forward-char 1))))
3259     (goto-char (point-max))
3260     (widen)
3261     (forward-line 1)))
3262
3263 (defun message-fill-references (header value)
3264   (insert (capitalize (symbol-name header))
3265           ": "
3266           (std11-fill-msg-id-list-string
3267           (if (consp value) (car value) value))
3268           "\n"))
3269
3270 (defun message-fill-header (header value)
3271   (let ((begin (point))
3272         (fill-column 78)
3273         (fill-prefix " "))
3274     (insert (capitalize (symbol-name header))
3275             ": "
3276             (if (consp value) (car value) value)
3277             "\n")
3278     (save-restriction
3279       (narrow-to-region begin (point))
3280       (fill-region-as-paragraph begin (point))
3281       ;; Tapdance around looong Message-IDs.
3282       (forward-line -1)
3283       (when (looking-at "[ \t]*$")
3284         (message-delete-line))
3285       (goto-char begin)
3286       (re-search-forward ":" nil t)
3287       (when (looking-at "\n[ \t]+")
3288         (replace-match " " t t))
3289       (goto-char (point-max)))))
3290
3291 (defun message-shorten-references (header references)
3292   "Limit REFERENCES to be shorter than 988 characters."
3293   (let ((max 988)
3294         (cut 4)
3295         refs)
3296     (nnheader-temp-write nil
3297       (insert references)
3298       (goto-char (point-min))
3299       (while (re-search-forward "<[^>]+>" nil t)
3300         (push (match-string 0) refs))
3301       (setq refs (nreverse refs))
3302       (while (> (length (mapconcat 'identity refs " ")) max)
3303         (when (< (length refs) (1+ cut))
3304           (decf cut))
3305         (setcdr (nthcdr cut refs) (cddr (nthcdr cut refs)))))
3306     (insert (capitalize (symbol-name header)) ": "
3307             (mapconcat 'identity refs " ") "\n")))
3308
3309 (defun message-position-point ()
3310   "Move point to where the user probably wants to find it."
3311   (message-narrow-to-headers)
3312   (cond
3313    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
3314     (search-backward ":" )
3315     (widen)
3316     (forward-char 1)
3317     (if (= (following-char) ? )
3318         (forward-char 1)
3319       (insert " ")))
3320    (t
3321     (goto-char (point-max))
3322     (widen)
3323     (forward-line 1)
3324     (unless (looking-at "$")
3325       (forward-line 2)))
3326    (sit-for 0)))
3327
3328 (defun message-buffer-name (type &optional to group)
3329   "Return a new (unique) buffer name based on TYPE and TO."
3330   (cond
3331    ;; Check whether `message-generate-new-buffers' is a function,
3332    ;; and if so, call it.
3333    ((message-functionp message-generate-new-buffers)
3334     (funcall message-generate-new-buffers type to group))
3335    ;; Generate a new buffer name The Message Way.
3336    (message-generate-new-buffers
3337     (generate-new-buffer-name
3338      (concat "*" type
3339              (if to
3340                  (concat " to "
3341                          (or (car (std11-extract-address-components to))
3342                              to) "")
3343                "")
3344              (if (and group (not (string= group ""))) (concat " on " group) "")
3345              "*")))
3346    ;; Use standard name.
3347    (t
3348     (format "*%s message*" type))))
3349
3350 (defun message-pop-to-buffer (name)
3351   "Pop to buffer NAME, and warn if it already exists and is modified."
3352   (let ((pop-up-frames pop-up-frames)
3353         (special-display-buffer-names special-display-buffer-names)
3354         (special-display-regexps special-display-regexps)
3355         (same-window-buffer-names same-window-buffer-names)
3356         (same-window-regexps same-window-regexps)
3357         (buffer (get-buffer name))
3358         (cur (current-buffer)))
3359     (if (or (and (featurep 'xemacs)
3360                  (not (eq 'tty (device-type))))
3361             window-system
3362             (>= emacs-major-version 20))
3363         (when message-use-multi-frames
3364           (setq pop-up-frames t
3365                 special-display-buffer-names nil
3366                 special-display-regexps nil
3367                 same-window-buffer-names nil
3368                 same-window-regexps nil))
3369       (setq pop-up-frames nil))
3370     (if (and buffer
3371              (buffer-name buffer))
3372         (progn
3373           (set-buffer (pop-to-buffer buffer))
3374           (when (and (buffer-modified-p)
3375                      (not (y-or-n-p
3376                            "Message already being composed; erase? ")))
3377             (error "Message being composed")))
3378       (set-buffer (pop-to-buffer name)))
3379     (erase-buffer)
3380     (message-mode)
3381     (when pop-up-frames
3382       (make-local-variable 'message-original-frame)
3383       (setq message-original-frame (selected-frame)))))
3384
3385 (defun message-do-send-housekeeping ()
3386   "Kill old message buffers."
3387   ;; We might have sent this buffer already.  Delete it from the
3388   ;; list of buffers.
3389   (setq message-buffer-list (delq (current-buffer) message-buffer-list))
3390   (while (and message-max-buffers
3391               message-buffer-list
3392               (>= (length message-buffer-list) message-max-buffers))
3393     ;; Kill the oldest buffer -- unless it has been changed.
3394     (let ((buffer (pop message-buffer-list)))
3395       (when (and (buffer-name buffer)
3396                  (not (buffer-modified-p buffer)))
3397         (kill-buffer buffer))))
3398   ;; Rename the buffer.
3399   (if message-send-rename-function
3400       (funcall message-send-rename-function)
3401     (when (string-match "\\`\\*" (buffer-name))
3402       (rename-buffer
3403        (concat "*sent " (substring (buffer-name) (match-end 0))) t)))
3404   ;; Push the current buffer onto the list.
3405   (when message-max-buffers
3406     (setq message-buffer-list
3407           (nconc message-buffer-list (list (current-buffer))))))
3408
3409 (defvar mc-modes-alist)
3410 (defun message-setup (headers &optional replybuffer actions)
3411   (when (and (boundp 'mc-modes-alist)
3412              (not (assq 'message-mode mc-modes-alist)))
3413     (push '(message-mode (encrypt . mc-encrypt-message)
3414                          (sign . mc-sign-message))
3415           mc-modes-alist))
3416   (when actions
3417     (setq message-send-actions actions))
3418   (setq message-reply-buffer replybuffer)
3419   (goto-char (point-min))
3420   ;; Insert all the headers.
3421   (mail-header-format
3422    (let ((h headers)
3423          (alist message-header-format-alist))
3424      (while h
3425        (unless (assq (caar h) message-header-format-alist)
3426          (push (list (caar h)) alist))
3427        (pop h))
3428      alist)
3429    headers)
3430   (delete-region (point) (progn (forward-line -1) (point)))
3431   (when message-default-headers
3432     (insert message-default-headers)
3433     (or (bolp) (insert ?\n)))
3434   (put-text-property
3435    (point)
3436    (progn
3437      (insert mail-header-separator "\n")
3438      (1- (point)))
3439    'read-only nil)
3440   (forward-line -1)
3441   (when (message-news-p)
3442     (when message-default-news-headers
3443       (insert message-default-news-headers)
3444       (or (bolp) (insert ?\n)))
3445     (when message-generate-headers-first
3446       (message-generate-headers
3447        (delq 'Lines
3448              (delq 'Subject
3449                    (copy-sequence message-required-news-headers))))))
3450   (when (message-mail-p)
3451     (when message-default-mail-headers
3452       (insert message-default-mail-headers)
3453       (or (bolp) (insert ?\n)))
3454     (when message-generate-headers-first
3455       (message-generate-headers
3456        (delq 'Lines
3457              (delq 'Subject
3458                    (copy-sequence message-required-mail-headers))))))
3459   (run-hooks 'message-signature-setup-hook)
3460   (message-insert-signature)
3461   (save-restriction
3462     (message-narrow-to-headers)
3463     (run-hooks 'message-header-setup-hook))
3464   (set-buffer-modified-p nil)
3465   (setq buffer-undo-list nil)
3466   (run-hooks 'message-setup-hook)
3467   (message-position-point)
3468   (undo-boundary))
3469
3470 (defun message-set-auto-save-file-name ()
3471   "Associate the message buffer with a file in the drafts directory."
3472   (when message-autosave-directory
3473     (if (gnus-alive-p)
3474         (setq message-draft-article
3475               (nndraft-request-associate-buffer "drafts"))
3476       (setq buffer-file-name (expand-file-name "*message*"
3477                                                message-autosave-directory))
3478       (setq buffer-auto-save-file-name (make-auto-save-file-name)))
3479     (clear-visited-file-modtime)))
3480
3481 (defun message-disassociate-draft ()
3482   "Disassociate the message buffer from the drafts directory."
3483   (when message-draft-article
3484     (nndraft-request-expire-articles
3485      (list message-draft-article) "drafts" nil t)))
3486
3487 \f
3488
3489 ;;;
3490 ;;; Commands for interfacing with message
3491 ;;;
3492
3493 ;;;###autoload
3494 (defun message-mail (&optional to subject
3495                                other-headers continue switch-function
3496                                yank-action send-actions)
3497   "Start editing a mail message to be sent.
3498 OTHER-HEADERS is an alist of header/value pairs."
3499   (interactive)
3500   (let ((message-this-is-mail t))
3501     (message-pop-to-buffer (message-buffer-name "mail" to))
3502     (message-setup
3503      (nconc
3504       `((To . ,(or to "")) (Subject . ,(or subject "")))
3505       (when other-headers other-headers)))))
3506
3507 ;;;###autoload
3508 (defun message-news (&optional newsgroups subject)
3509   "Start editing a news article to be sent."
3510   (interactive)
3511   (let ((message-this-is-news t))
3512     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups))
3513     (message-setup `((Newsgroups . ,(or newsgroups ""))
3514                      (Subject . ,(or subject ""))))))
3515
3516 ;;;###autoload
3517 (defun message-reply (&optional to-address wide)
3518   "Start editing a reply to the article in the current buffer."
3519   (interactive)
3520   (let ((cur (current-buffer))
3521         (inhibit-point-motion-hooks t)
3522         from date subject mct mft mrt
3523         never-mct to cc
3524         references message-id follow-to gnus-warning)
3525     (save-restriction
3526       (message-narrow-to-head)
3527       ;; Allow customizations to have their say.
3528       (if (not wide)
3529           ;; This is a regular reply.
3530           (if (message-functionp message-reply-to-function)
3531               (setq follow-to (funcall message-reply-to-function)))
3532         ;; This is a followup.
3533         (if (message-functionp message-wide-reply-to-function)
3534             (save-excursion
3535               (setq follow-to
3536                     (funcall message-wide-reply-to-function)))))
3537       ;; Find all relevant headers we need.
3538       (setq from (message-fetch-field "from")
3539             date (message-fetch-field "date" t)
3540             subject (or (message-fetch-field "subject") "none")
3541             references (message-fetch-field "references")
3542             message-id (message-fetch-field "message-id" t)
3543             to (message-fetch-field "to")
3544             cc (message-fetch-field "cc")
3545             mct (when (and wide message-use-mail-copies-to)
3546                   (message-fetch-field "mail-copies-to"))
3547             mft (when (and wide message-use-mail-followup-to)
3548                   (message-fetch-field "mail-followup-to"))
3549             mrt (when message-use-mail-reply-to
3550                   (or (message-fetch-field "mail-reply-to")
3551                       (message-fetch-field "reply-to")))
3552             gnus-warning (message-fetch-field "gnus-warning"))
3553       (when (and gnus-warning (string-match "<[^>]+>" gnus-warning))
3554         (setq message-id (match-string 0 gnus-warning)))
3555       ;; Remove any (buggy) Re:'s that are present and make a
3556       ;; proper one.
3557       (setq subject (message-make-followup-subject subject))
3558       (widen))
3559
3560     ;; Handle special values of Mail-Copies-To.
3561     (when mct
3562       (cond
3563        ((and (equal (downcase mct) "never")
3564              (or (not (eq message-use-mail-copies-to 'ask))
3565                  (message-y-or-n-p
3566                   (concat "Obey Mail-Copies-To: never? ") t "\
3567 You should normally obey the Mail-Copies-To: header.
3568
3569         `Mail-Copies-To: never'
3570 directs you not to send your response to the author.")))
3571         (setq never-mct t)
3572         (setq mct nil))
3573        ((and (equal (downcase mct) "always")
3574              (or (not (eq message-use-mail-copies-to 'ask))
3575                  (message-y-or-n-p
3576                   (concat "Obey Mail-Copies-To: always? ") t "\
3577 You should normally obey the Mail-Copies-To: header.
3578
3579         `Mail-Copies-To: always'
3580 sends a copy of your response to the author.")))
3581         (setq mct (or mrt from)))
3582        ((and (eq message-use-mail-copies-to 'ask)
3583              (not 
3584               (message-y-or-n-p
3585                (concat "Obey Mail-Copies-To: " mct " ? ") t "\
3586 You should normally obey the Mail-Copies-To: header.
3587
3588         `Mail-Copies-To: " mct "'
3589 sends a copy of your response to " (if (string-match "," mct)
3590                                        "the specified addresses"
3591                                      "that address") ".")))
3592         (setq mct nil))
3593        ))
3594
3595     (unless follow-to
3596       (cond
3597        (to-address (setq follow-to (list (cons 'To to-address))))
3598        ((not wide) (setq follow-to (list (cons 'To (or mrt from)))))
3599        ;; Handle Mail-Followup-To.
3600        ((and mft
3601              (or (not (eq message-use-mail-followup-to 'ask))
3602                  (message-y-or-n-p
3603                   (concat "Obey Mail-Followup-To: " mft "? ") t "\
3604 You should normally obey the Mail-Followup-To: header.
3605
3606         `Mail-Followup-To: " mft "'
3607 directs your response to " (if (string-match "," mft)
3608                                "the specified addresses"
3609                              "that address only") ".
3610
3611 A typical situation where Mail-Followup-To is used is when the author thinks
3612 that further discussion should take place only in "
3613                   (if (string-match "," mft)
3614                       "the specified mailing lists"
3615                     "that mailing list") ".")))
3616         (setq follow-to (list (cons 'To mft)))
3617         (when mct
3618           (push (cons 'Cc mct) follow-to)))
3619        (t
3620         (let (ccalist)
3621           (save-excursion
3622             (message-set-work-buffer)
3623             (unless never-mct
3624               (insert (or mrt from "")))
3625             (insert (if to (concat (if (bolp) "" ", ") to "") ""))
3626             (insert (if mct (concat (if (bolp) "" ", ") mct) ""))
3627             (insert (if cc (concat (if (bolp) "" ", ") cc) ""))
3628             (goto-char (point-min))
3629             (while (re-search-forward "[ \t]+" nil t)
3630               (replace-match " " t t))
3631             ;; Remove addresses that match `rmail-dont-reply-to-names'.
3632             (insert (prog1 (rmail-dont-reply-to (buffer-string))
3633                       (erase-buffer)))
3634             (goto-char (point-min))
3635             ;; Perhaps Mail-Copies-To: never removed the only address?
3636             (when (eobp)
3637               (insert (or mrt from "")))
3638             (setq ccalist
3639                   (mapcar
3640                    (lambda (addr)
3641                      (cons (mail-strip-quoted-names addr) addr))
3642                    (message-tokenize-header (buffer-string))))
3643             (let ((s ccalist))
3644               (while s
3645                 (setq ccalist (delq (assoc (car (pop s)) s) ccalist)))))
3646           (setq follow-to (list (cons 'To (cdr (pop ccalist)))))
3647           (when ccalist
3648             (let ((ccs (cons 'Cc (mapconcat
3649                                   (lambda (addr) (cdr addr)) ccalist ", "))))
3650               (when (string-match "^ +" (cdr ccs))
3651                 (setcdr ccs (substring (cdr ccs) (match-end 0))))
3652               (push ccs follow-to)))))))
3653
3654     (message-pop-to-buffer (message-buffer-name
3655                             (if wide "wide reply" "reply") from
3656                             (if wide to-address nil)))
3657
3658     (setq message-reply-headers
3659           (vector 0 subject from date message-id references 0 0 ""))
3660
3661     (message-setup
3662      `((Subject . ,subject)
3663        ,@follow-to
3664        ,@(if (or references message-id)
3665              `((References . ,(concat (or references "") (and references " ")
3666                                       (or message-id ""))))))
3667      cur)))
3668
3669 ;;;###autoload
3670 (defun message-wide-reply (&optional to-address)
3671   "Make a \"wide\" reply to the message in the current buffer."
3672   (interactive)
3673   (message-reply to-address t))
3674
3675 ;;;###autoload
3676 (defun message-followup (&optional to-newsgroups)
3677   "Follow up to the message in the current buffer."
3678   (interactive)
3679   (let ((cur (current-buffer))
3680         (inhibit-point-motion-hooks t)
3681         from date subject mct mft mrt
3682         (message-this-is-news t)
3683         followup-to distribution newsgroups posted-to
3684         references message-id follow-to gnus-warning)
3685     (save-restriction
3686       (message-narrow-to-head)
3687       ;; Allow customizations to have their say.
3688       ;; This is a followup.
3689       (when (message-functionp message-followup-to-function)
3690         (setq follow-to
3691               (funcall message-followup-to-function)))
3692       ;; Find all relevant headers we need.
3693       (setq from (message-fetch-field "from")
3694             date (message-fetch-field "date" t)
3695             subject (or (message-fetch-field "subject") "none")
3696             references (message-fetch-field "references")
3697             message-id (message-fetch-field "message-id" t)
3698             followup-to (when message-use-followup-to
3699                           (message-fetch-field "followup-to"))
3700             distribution (message-fetch-field "distribution")
3701             newsgroups (message-fetch-field "newsgroups")
3702             posted-to (message-fetch-field "posted-to")
3703             mct (when message-use-mail-copies-to
3704                   (message-fetch-field "mail-copies-to"))
3705             mft (when message-use-mail-followup-to
3706                   (message-fetch-field "mail-followup-to"))
3707             mrt (when message-use-mail-reply-to
3708                   (or (message-fetch-field "mail-reply-to")
3709                       (message-fetch-field "reply-to")))
3710             gnus-warning (message-fetch-field "gnus-warning"))
3711       (when (and gnus-warning (string-match "<[^>]+>" gnus-warning))
3712         (setq message-id (match-string 0 gnus-warning)))
3713       ;; Remove bogus distribution.
3714       (when (and (stringp distribution)
3715                  (let ((case-fold-search t))
3716                    (string-match "world" distribution)))
3717         (setq distribution nil))
3718       ;; Remove any (buggy) Re:'s that are present and make a
3719       ;; proper one.
3720       (setq subject (message-make-followup-subject subject))
3721       (widen))
3722
3723     ;; Handle special values of Mail-Copies-To.
3724     (when mct
3725       (cond
3726        ((and (equal (downcase mct) "never")
3727              (or (not (eq message-use-mail-copies-to 'ask))
3728                  (message-y-or-n-p
3729                   (concat "Obey Mail-Copies-To: never? ") t "\
3730 You should normally obey the Mail-Copies-To: header.
3731
3732         `Mail-Copies-To: never'
3733 directs you not to send your response to the author.")))
3734         (setq mct nil))
3735        ((and (equal (downcase mct) "always")
3736              (or (not (eq message-use-mail-copies-to 'ask))
3737                  (message-y-or-n-p
3738                   (concat "Obey Mail-Copies-To: always? ") t "\
3739 You should normally obey the Mail-Copies-To: header.
3740
3741         `Mail-Copies-To: always'
3742 sends a copy of your response to the author.")))
3743         (setq mct (or mrt from)))
3744        ((and (eq message-use-mail-copies-to 'ask)
3745              (not 
3746               (message-y-or-n-p
3747                (concat "Obey Mail-Copies-To: " mct " ? ") t "\
3748 You should normally obey the Mail-Copies-To: header.
3749
3750         `Mail-Copies-To: " mct "'
3751 sends a copy of your response to " (if (string-match "," mct)
3752                                        "the specified addresses"
3753                                      "that address") ".")))
3754         (setq mct nil))
3755        ))
3756
3757     (unless follow-to
3758       (cond
3759        (to-newsgroups (setq follow-to (list (cons 'Newsgroups to-newsgroups))))
3760        ;; Handle Followup-To.
3761        (followup-to
3762         (cond
3763          ((equal (downcase followup-to) "poster")
3764           (if (or (eq message-use-followup-to 'use)
3765                   (message-y-or-n-p "Obey Followup-To: poster? " t "\
3766 You should normally obey the Followup-To: header.
3767
3768         `Followup-To: poster'
3769 sends your response via e-mail instead of news.
3770
3771 A typical situation where `Followup-To: poster' is used is when the author
3772 does not read the newsgroup, so he wouldn't see any replies sent to it."))
3773               (setq message-this-is-news nil
3774                     distribution nil
3775                     follow-to (list (cons 'To (or mrt from ""))))
3776             (setq follow-to (list (cons 'Newsgroups newsgroups)))))
3777          (t
3778           (if (or (equal followup-to newsgroups)
3779                   (not (eq message-use-followup-to 'ask))
3780                   (message-y-or-n-p
3781                    (concat "Obey Followup-To: " followup-to "? ") t "\
3782 You should normally obey the Followup-To: header.
3783
3784         `Followup-To: " followup-to "'
3785 directs your response to " (if (string-match "," followup-to)
3786                                "the specified newsgroups"
3787                              "that newsgroup only") ".
3788
3789 If a message is posted to several newsgroups, Followup-To is often
3790 used to direct the following discussion to one newsgroup only,
3791 because discussions that are spread over several newsgroup tend to
3792 be fragmented and very difficult to follow.
3793
3794 Also, some source/announcement newsgroups are not indented for discussion;
3795 responses here are directed to other newsgroups."))
3796               (setq follow-to (list (cons 'Newsgroups followup-to)))
3797             (setq follow-to (list (cons 'Newsgroups newsgroups)))))))
3798        ;; Handle Mail-Followup-To, followup via e-mail.
3799        ((and mft
3800              (or (not (eq message-use-mail-followup-to 'ask))
3801                  (message-y-or-n-p
3802                   (concat "Obey Mail-Followup-To: " mft "? ") t "\
3803 You should normally obey the Mail-Followup-To: header.
3804
3805         `Mail-Followup-To: " mft "'
3806 directs your response to " (if (string-match "," mft)
3807                                "the specified addresses"
3808                              "that address only") " instead of news.
3809
3810 A typical situation where Mail-Followup-To is used is when the author thinks
3811 that further discussion should take place only in "
3812                              (if (string-match "," mft)
3813                                  "the specified mailing lists"
3814                                "that mailing list") ".")))
3815         (setq message-this-is-news nil
3816               distribution nil
3817               follow-to (list (cons 'To mft))))
3818        (posted-to (setq follow-to (list (cons 'Newsgroups posted-to))))
3819        (t
3820         (setq follow-to (list (cons 'Newsgroups newsgroups))))))
3821
3822     (message-pop-to-buffer (message-buffer-name "followup" from newsgroups))
3823
3824     (setq message-reply-headers
3825           (vector 0 subject from date message-id references 0 0 ""))
3826
3827     (message-setup
3828      `((Subject . ,subject)
3829        ,@follow-to
3830        ,@(and mct (list (cons 'Cc mct)))
3831        ,@(and distribution (list (cons 'Distribution distribution)))
3832        ,@(if (or references message-id)
3833              `((References . ,(concat (or references "") (and references " ")
3834                                       (or message-id ""))))))
3835      cur)))
3836
3837 ;;;###autoload
3838 (defun message-cancel-news ()
3839   "Cancel an article you posted."
3840   (interactive)
3841   (unless (message-news-p)
3842     (error "This is not a news article; canceling is impossible"))
3843   (when (yes-or-no-p "Do you really want to cancel this article? ")
3844     (let (from newsgroups message-id distribution buf sender)
3845       (save-excursion
3846         ;; Get header info. from original article.
3847         (save-restriction
3848           (message-narrow-to-head)
3849           (setq from (message-fetch-field "from")
3850                 sender (message-fetch-field "sender")
3851                 newsgroups (message-fetch-field "newsgroups")
3852                 message-id (message-fetch-field "message-id" t)
3853                 distribution (message-fetch-field "distribution")))
3854         ;; Make sure that this article was written by the user.
3855         (unless (or (and sender
3856                          (string-equal
3857                           (downcase sender)
3858                           (downcase (message-make-sender))))
3859                     (string-equal
3860                      (downcase (cadr (std11-extract-address-components
3861                                       from)))
3862                      (downcase (cadr (std11-extract-address-components
3863                                       (message-make-from))))))
3864           (error "This article is not yours"))
3865         ;; Make control message.
3866         (setq buf (set-buffer (get-buffer-create " *message cancel*")))
3867         (buffer-disable-undo (current-buffer))
3868         (erase-buffer)
3869         (insert "Newsgroups: " newsgroups "\n"
3870                 "From: " (message-make-from) "\n"
3871                 "Subject: cmsg cancel " message-id "\n"
3872                 "Control: cancel " message-id "\n"
3873                 (if distribution
3874                     (concat "Distribution: " distribution "\n")
3875                   "")
3876                 mail-header-separator "\n"
3877                 message-cancel-message)
3878         (message "Canceling your article...")
3879         (if (let ((message-syntax-checks
3880                    'dont-check-for-anything-just-trust-me)
3881                   (message-encoding-buffer (current-buffer))
3882                   (message-edit-buffer (current-buffer)))
3883               (message-send-news))
3884             (message "Canceling your article...done"))
3885         (kill-buffer buf)))))
3886
3887 ;;;###autoload
3888 (defun message-supersede ()
3889   "Start composing a message to supersede the current message.
3890 This is done simply by taking the old article and adding a Supersedes
3891 header line with the old Message-ID."
3892   (interactive)
3893   (let ((cur (current-buffer)))
3894     ;; Check whether the user owns the article that is to be superseded.
3895     (unless (string-equal
3896              (downcase (or (message-fetch-field "sender")
3897                            (cadr (std11-extract-address-components
3898                                   (message-fetch-field "from")))))
3899              (downcase (message-make-sender)))
3900       (error "This article is not yours"))
3901     ;; Get a normal message buffer.
3902     (message-pop-to-buffer (message-buffer-name "supersede"))
3903     (insert-buffer-substring cur)
3904     (message-narrow-to-head)
3905     ;; Remove unwanted headers.
3906     (when message-ignored-supersedes-headers
3907       (message-remove-header message-ignored-supersedes-headers t))
3908     (goto-char (point-min))
3909     (if (not (re-search-forward "^Message-ID: " nil t))
3910         (error "No Message-ID in this article")
3911       (replace-match "Supersedes: " t t))
3912     (goto-char (point-max))
3913     (insert mail-header-separator)
3914     (widen)
3915     (forward-line 1)))
3916
3917 ;;;###autoload
3918 (defun message-recover ()
3919   "Reread contents of current buffer from its last auto-save file."
3920   (interactive)
3921   (let ((file-name (make-auto-save-file-name)))
3922     (cond ((save-window-excursion
3923              (if (not (eq system-type 'vax-vms))
3924                  (with-output-to-temp-buffer "*Directory*"
3925                    (buffer-disable-undo standard-output)
3926                    (let ((default-directory "/"))
3927                      (call-process
3928                       "ls" nil standard-output nil "-l" file-name))))
3929              (yes-or-no-p (format "Recover auto save file %s? " file-name)))
3930            (let ((buffer-read-only nil))
3931              (erase-buffer)
3932              (insert-file-contents file-name nil)))
3933           (t (error "message-recover cancelled")))))
3934
3935 ;;; Washing Subject:
3936
3937 (defun message-wash-subject (subject)
3938   "Remove junk like \"Re:\", \"(fwd)\", etc. that was added to the subject by previous forwarders, replyers, etc."
3939   (nnheader-temp-write nil
3940     (insert-string subject)
3941     (goto-char (point-min))
3942     ;; strip Re/Fwd stuff off the beginning
3943     (while (re-search-forward
3944             "\\([Rr][Ee]:\\|[Ff][Ww][Dd]:\\|[Ff][Ww]:\\)" nil t)
3945       (replace-match ""))
3946
3947     ;; and gnus-style forwards [foo@bar.com] subject
3948     (goto-char (point-min))
3949     (while (re-search-forward "\\[[^ \t]*\\(@\\|\\.\\)[^ \t]*\\]" nil t)
3950       (replace-match ""))
3951
3952     ;; and off the end
3953     (goto-char (point-max))
3954     (while (re-search-backward "([Ff][Ww][Dd])" nil t)
3955       (replace-match ""))
3956
3957     ;; and finally, any whitespace that was left-over
3958     (goto-char (point-min))
3959     (while (re-search-forward "^[ \t]+" nil t)
3960       (replace-match ""))
3961     (goto-char (point-max))
3962     (while (re-search-backward "[ \t]+$" nil t)
3963       (replace-match ""))
3964
3965     (buffer-string)))
3966     
3967 ;;; Forwarding messages.
3968
3969 (defun message-forward-subject-author-subject (subject)
3970   "Generate a subject for a forwarded message.
3971 The form is: [Source] Subject, where if the original message was mail,
3972 Source is the sender, and if the original message was news, Source is
3973 the list of newsgroups is was posted to."
3974   (concat "["
3975           (or (message-fetch-field
3976                (if (message-news-p) "newsgroups" "from"))
3977               "(nowhere)")
3978           "] " subject))
3979
3980 (defun message-forward-subject-fwd (subject)
3981   "Generate a subject for a forwarded message.
3982 The form is: Fwd: Subject, where Subject is the original subject of
3983 the message."
3984   (concat "Fwd: " subject))
3985
3986 (defun message-make-forward-subject ()
3987   "Return a Subject header suitable for the message in the current buffer."
3988   (save-excursion
3989     (save-restriction
3990       (current-buffer)
3991       (message-narrow-to-head)
3992       (let ((funcs message-make-forward-subject-function)
3993             (subject (if message-wash-forwarded-subjects
3994                          (message-wash-subject
3995                           (or (eword-decode-unstructured-field-body
3996                                (message-fetch-field "Subject")) ""))
3997                        (or (eword-decode-unstructured-field-body
3998                             (message-fetch-field "Subject")) ""))))
3999         ;; Make sure funcs is a list.
4000         (and funcs
4001              (not (listp funcs))
4002              (setq funcs (list funcs)))
4003         ;; Apply funcs in order, passing subject generated by previous
4004         ;; func to the next one.
4005         (while funcs
4006           (when (message-functionp (car funcs))
4007             (setq subject (funcall (car funcs) subject)))
4008           (setq funcs (cdr funcs)))
4009         subject))))
4010
4011 ;;;###autoload
4012 (defun message-forward (&optional news)
4013   "Forward the current message via mail.
4014 Optional NEWS will use news to forward instead of mail."
4015   (interactive "P")
4016   (let ((cur (current-buffer))
4017         (subject (message-make-forward-subject))
4018         art-beg)
4019     (if news (message-news nil subject) (message-mail nil subject))
4020     ;; Put point where we want it before inserting the forwarded
4021     ;; message.
4022     (if message-signature-before-forwarded-message
4023         (goto-char (point-max))
4024       (message-goto-body))
4025     ;; Make sure we're at the start of the line.
4026     (unless (eolp)
4027       (insert "\n"))
4028     ;; Narrow to the area we are to insert.
4029     (narrow-to-region (point) (point))
4030     ;; Insert the separators and the forwarded buffer.
4031     (insert message-forward-start-separator)
4032     (setq art-beg (point))
4033     (insert-buffer-substring cur)
4034     (goto-char (point-max))
4035     (insert message-forward-end-separator)
4036     (set-text-properties (point-min) (point-max) nil)
4037     ;; Remove all unwanted headers.
4038     (goto-char art-beg)
4039     (narrow-to-region (point) (if (search-forward "\n\n" nil t)
4040                                   (1- (point))
4041                                 (point)))
4042     (goto-char (point-min))
4043     (message-remove-header message-included-forward-headers t nil t)
4044     (widen)
4045     (message-position-point)))
4046
4047 ;;;###autoload
4048 (defun message-resend (address)
4049   "Resend the current article to ADDRESS."
4050   (interactive "sResend message to: ")
4051   (message "Resending message to %s..." address)
4052   (save-excursion
4053     (let ((cur (current-buffer))
4054           beg)
4055       ;; We first set up a normal mail buffer.
4056       (set-buffer (get-buffer-create " *message resend*"))
4057       (buffer-disable-undo (current-buffer))
4058       (erase-buffer)
4059       ;; avoid to turn-on-mime-edit
4060       (let (message-setup-hook)
4061         (message-setup `((To . ,address)))
4062         )
4063       ;; Insert our usual headers.
4064       (message-generate-headers '(From Date To))
4065       (message-narrow-to-headers)
4066       ;; Rename them all to "Resent-*".
4067       (while (re-search-forward "^[A-Za-z]" nil t)
4068         (forward-char -1)
4069         (insert "Resent-"))
4070       (widen)
4071       (forward-line)
4072       (delete-region (point) (point-max))
4073       (setq beg (point))
4074       ;; Insert the message to be resent.
4075       (insert-buffer-substring cur)
4076       (goto-char (point-min))
4077       (search-forward "\n\n")
4078       (forward-char -1)
4079       (save-restriction
4080         (narrow-to-region beg (point))
4081         (message-remove-header message-ignored-resent-headers t)
4082         (goto-char (point-max)))
4083       (insert mail-header-separator)
4084       ;; Rename all old ("Also-")Resent headers.
4085       (while (re-search-backward "^\\(Also-\\)*Resent-" beg t)
4086         (beginning-of-line)
4087         (insert "Also-"))
4088       ;; Quote any "From " lines at the beginning.
4089       (goto-char beg)
4090       (when (looking-at "From ")
4091         (replace-match "X-From-Line: "))
4092       ;; Send it.
4093       (let ((message-encoding-buffer (current-buffer))
4094             (message-edit-buffer (current-buffer)))
4095         (message-send-mail))
4096       (kill-buffer (current-buffer)))
4097     (message "Resending message to %s...done" address)))
4098
4099 ;;;###autoload
4100 (defun message-bounce ()
4101   "Re-mail the current message.
4102 This only makes sense if the current message is a bounce message than
4103 contains some mail you have written which has been bounced back to
4104 you."
4105   (interactive)
4106   (let ((cur (current-buffer))
4107         boundary)
4108     (message-pop-to-buffer (message-buffer-name "bounce"))
4109     (insert-buffer-substring cur)
4110     (undo-boundary)
4111     (message-narrow-to-head)
4112     (if (and (message-fetch-field "MIME-Version")
4113              (setq boundary (message-fetch-field "Content-Type")))
4114         (if (string-match "boundary=\"\\([^\"]+\\)\"" boundary)
4115             (setq boundary (concat (match-string 1 boundary) " *\n"
4116                                    "Content-Type: message/rfc822"))
4117           (setq boundary nil)))
4118     (widen)
4119     (goto-char (point-min))
4120     (search-forward "\n\n" nil t)
4121     (or (and boundary
4122              (re-search-forward boundary nil t)
4123              (forward-line 2))
4124         (and (re-search-forward message-unsent-separator nil t)
4125              (forward-line 1))
4126         (re-search-forward "^Return-Path:.*\n" nil t))
4127     ;; We remove everything before the bounced mail.
4128     (delete-region
4129      (point-min)
4130      (if (re-search-forward "^[^ \n\t]+:" nil t)
4131          (match-beginning 0)
4132        (point)))
4133     (save-restriction
4134       (message-narrow-to-head)
4135       (message-remove-header message-ignored-bounced-headers t)
4136       (goto-char (point-max))
4137       (insert mail-header-separator))
4138     (message-position-point)))
4139
4140 ;;;
4141 ;;; Interactive entry points for new message buffers.
4142 ;;;
4143
4144 ;;;###autoload
4145 (defun message-mail-other-window (&optional to subject)
4146   "Like `message-mail' command, but display mail buffer in another window."
4147   (interactive)
4148   (let ((pop-up-windows t)
4149         (special-display-buffer-names nil)
4150         (special-display-regexps nil)
4151         (same-window-buffer-names nil)
4152         (same-window-regexps nil))
4153     (message-pop-to-buffer (message-buffer-name "mail" to)))
4154   (let ((message-this-is-mail t))
4155     (message-setup `((To . ,(or to "")) (Subject . ,(or subject ""))))))
4156
4157 ;;;###autoload
4158 (defun message-mail-other-frame (&optional to subject)
4159   "Like `message-mail' command, but display mail buffer in another frame."
4160   (interactive)
4161   (let ((pop-up-frames t)
4162         (special-display-buffer-names nil)
4163         (special-display-regexps nil)
4164         (same-window-buffer-names nil)
4165         (same-window-regexps nil))
4166     (message-pop-to-buffer (message-buffer-name "mail" to)))
4167   (let ((message-this-is-mail t))
4168     (message-setup `((To . ,(or to "")) (Subject . ,(or subject ""))))))
4169
4170 ;;;###autoload
4171 (defun message-news-other-window (&optional newsgroups subject)
4172   "Start editing a news article to be sent."
4173   (interactive)
4174   (let ((pop-up-windows t)
4175         (special-display-buffer-names nil)
4176         (special-display-regexps nil)
4177         (same-window-buffer-names nil)
4178         (same-window-regexps nil))
4179     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
4180   (let ((message-this-is-news t))
4181     (message-setup `((Newsgroups . ,(or newsgroups ""))
4182                      (Subject . ,(or subject ""))))))
4183
4184 ;;;###autoload
4185 (defun message-news-other-frame (&optional newsgroups subject)
4186   "Start editing a news article to be sent."
4187   (interactive)
4188   (let ((pop-up-frames t)
4189         (special-display-buffer-names nil)
4190         (special-display-regexps nil)
4191         (same-window-buffer-names nil)
4192         (same-window-regexps nil))
4193     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
4194   (let ((message-this-is-news t))
4195     (message-setup `((Newsgroups . ,(or newsgroups ""))
4196                      (Subject . ,(or subject ""))))))
4197
4198 ;;; underline.el
4199
4200 ;; This code should be moved to underline.el (from which it is stolen).
4201
4202 ;;;###autoload
4203 (defun bold-region (start end)
4204   "Bold all nonblank characters in the region.
4205 Works by overstriking characters.
4206 Called from program, takes two arguments START and END
4207 which specify the range to operate on."
4208   (interactive "r")
4209   (save-excursion
4210     (let ((end1 (make-marker)))
4211       (move-marker end1 (max start end))
4212       (goto-char (min start end))
4213       (while (< (point) end1)
4214         (or (looking-at "[_\^@- ]")
4215             (insert (following-char) "\b"))
4216         (forward-char 1)))))
4217
4218 ;;;###autoload
4219 (defun unbold-region (start end)
4220   "Remove all boldness (overstruck characters) in the region.
4221 Called from program, takes two arguments START and END
4222 which specify the range to operate on."
4223   (interactive "r")
4224   (save-excursion
4225     (let ((end1 (make-marker)))
4226       (move-marker end1 (max start end))
4227       (goto-char (min start end))
4228       (while (re-search-forward "\b" end1 t)
4229         (if (eq (following-char) (char-after (- (point) 2)))
4230             (delete-char -2))))))
4231
4232 (defalias 'message-exchange-point-and-mark 'exchange-point-and-mark)
4233
4234 ;; Support for toolbar
4235 (when (string-match "XEmacs\\|Lucid" emacs-version)
4236   (require 'messagexmas))
4237
4238 ;;; Group name completion.
4239
4240 (defvar message-newgroups-header-regexp
4241   "^\\(Newsgroups\\|Followup-To\\|Posted-To\\|Gcc\\):"
4242   "Regexp that match headers that lists groups.")
4243
4244 (defun message-tab ()
4245   "Expand group names in Newsgroups and Followup-To headers.
4246 Do a `tab-to-tab-stop' if not in those headers."
4247   (interactive)
4248   (if (let ((mail-abbrev-mode-regexp message-newgroups-header-regexp))
4249         (mail-abbrev-in-expansion-header-p))
4250       (message-expand-group)
4251     (tab-to-tab-stop)))
4252
4253 (defvar gnus-active-hashtb)
4254 (defun message-expand-group ()
4255   "Expand the group name under point."
4256   (let* ((b (save-excursion
4257               (save-restriction
4258                 (narrow-to-region
4259                  (save-excursion
4260                    (beginning-of-line)
4261                    (skip-chars-forward "^:")
4262                    (1+ (point)))
4263                  (point))
4264                 (skip-chars-backward "^, \t\n") (point))))
4265          (completion-ignore-case t)
4266          (string (buffer-substring b (progn (skip-chars-forward "^,\t\n ")
4267                                             (point))))
4268          (hashtb (and (boundp 'gnus-active-hashtb) gnus-active-hashtb))
4269          (completions (all-completions string hashtb))
4270          (cur (current-buffer))
4271          comp)
4272     (delete-region b (point))
4273     (cond
4274      ((= (length completions) 1)
4275       (if (string= (car completions) string)
4276           (progn
4277             (insert string)
4278             (message "Only matching group"))
4279         (insert (car completions))))
4280      ((and (setq comp (try-completion string hashtb))
4281            (not (string= comp string)))
4282       (insert comp))
4283      (t
4284       (insert string)
4285       (if (not comp)
4286           (message "No matching groups")
4287         (save-selected-window
4288           (pop-to-buffer "*Completions*")
4289           (buffer-disable-undo (current-buffer))
4290           (let ((buffer-read-only nil))
4291             (erase-buffer)
4292             (let ((standard-output (current-buffer)))
4293               (display-completion-list (sort completions 'string<)))
4294             (goto-char (point-min))
4295             (delete-region (point) (progn (forward-line 3) (point))))))))))
4296
4297 ;;; Help stuff.
4298
4299 (defun message-talkative-question (ask question show &rest text)
4300   "Call FUNCTION with argument QUESTION; optionally display TEXT... args.
4301 If SHOW is non-nil, the arguments TEXT... are displayed in a temp buffer.
4302 The following arguments may contain lists of values."
4303   (if (and show
4304            (setq text (message-flatten-list text)))
4305       (save-window-excursion
4306         (save-excursion
4307           (with-output-to-temp-buffer " *MESSAGE information message*"
4308             (set-buffer " *MESSAGE information message*")
4309             (mapcar 'princ text)
4310             (goto-char (point-min))))
4311         (funcall ask question))
4312     (funcall ask question)))
4313
4314 (defun message-flatten-list (list)
4315   "Return a new, flat list that contains all elements of LIST.
4316
4317 \(message-flatten-list '(1 (2 3 (4 5 (6))) 7))
4318 => (1 2 3 4 5 6 7)"
4319   (cond ((consp list)
4320          (apply 'append (mapcar 'message-flatten-list list)))
4321         (list
4322          (list list))))
4323
4324 (defun message-generate-new-buffer-clone-locals (name &optional varstr)
4325   "Create and return a buffer with a name based on NAME using generate-new-buffer.
4326 Then clone the local variables and values from the old buffer to the
4327 new one, cloning only the locals having a substring matching the
4328 regexp varstr."
4329   (let ((oldbuf (current-buffer)))
4330     (save-excursion
4331       (set-buffer (generate-new-buffer name))
4332       (message-clone-locals oldbuf)
4333       (current-buffer))))
4334
4335 (defun message-clone-locals (buffer)
4336   "Clone the local variables from BUFFER to the current buffer."
4337   (let ((locals (save-excursion
4338                   (set-buffer buffer)
4339                   (buffer-local-variables)))
4340         (regexp "^gnus\\|^nn\\|^message"))
4341     (mapcar
4342      (lambda (local)
4343        (when (and (consp local)
4344                   (car local)
4345                   (string-match regexp (symbol-name (car local))))
4346          (ignore-errors
4347            (set (make-local-variable (car local))
4348                 (cdr local)))))
4349      locals)))
4350
4351
4352 ;;; @ for MIME Edit mode
4353 ;;;
4354
4355 (defun message-maybe-setup-default-charset ()
4356   (let ((charset
4357          (and (boundp 'gnus-summary-buffer)
4358               (buffer-live-p gnus-summary-buffer)
4359               (save-excursion
4360                 (set-buffer gnus-summary-buffer)
4361                 default-mime-charset))))
4362     (if charset
4363         (progn
4364           (make-local-variable 'default-mime-charset)
4365           (setq default-mime-charset charset)
4366           ))))
4367
4368 (defun message-maybe-encode ()
4369   (when message-mime-mode
4370     (run-hooks 'mime-edit-translate-hook)
4371     (if (catch 'mime-edit-error
4372           (save-excursion
4373             (mime-edit-translate-body)
4374             ))
4375         (error "Translation error!")
4376       )
4377     (end-of-invisible)
4378     (run-hooks 'mime-edit-exit-hook)
4379     ))
4380
4381 (defun message-mime-insert-article (&optional message)
4382   (interactive)
4383   (let ((message-cite-function 'mime-edit-inserted-message-filter)
4384         (message-reply-buffer gnus-original-article-buffer)
4385         )
4386     (message-yank-original nil)
4387     ))
4388
4389 (set-alist 'mime-edit-message-inserter-alist
4390            'message-mode (function message-mime-insert-article))
4391
4392 ;;; Miscellaneous functions
4393
4394 ;; stolen (and renamed) from nnheader.el
4395 (defun message-replace-chars-in-string (string from to)
4396   "Replace characters in STRING from FROM to TO."
4397   (let ((string (substring string 0))   ;Copy string.
4398         (len (length string))
4399         (idx 0))
4400     ;; Replace all occurrences of FROM with TO.
4401     (while (< idx len)
4402       (when (= (aref string idx) from)
4403         (aset string idx to))
4404       (setq idx (1+ idx)))
4405     string))
4406
4407 (run-hooks 'message-load-hook)
4408
4409 (provide 'message)
4410
4411 ;;; message.el ends here