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