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