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