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