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