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