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