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