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