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