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