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