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