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