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