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