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