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