4929c84e77ee819e4bea218b1db59666a6a5424e
[elisp/gnus.git-] / 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-Y" 'message-yank-buffer)
1304   (define-key message-mode-map "\C-c\C-q" 'message-fill-yanked-message)
1305   (define-key message-mode-map "\C-c\C-w" 'message-insert-signature)
1306   (define-key message-mode-map "\C-c\M-h" 'message-insert-headers)
1307   (define-key message-mode-map "\C-c\C-r" 'message-caesar-buffer-body)
1308   (define-key message-mode-map "\C-c\C-o" 'message-sort-headers)
1309   (define-key message-mode-map "\C-c\M-r" 'message-rename-buffer)
1310
1311   (define-key message-mode-map "\C-c\C-c" 'message-send-and-exit)
1312   (define-key message-mode-map "\C-c\C-s" 'message-send)
1313   (define-key message-mode-map "\C-c\C-k" 'message-kill-buffer)
1314   (define-key message-mode-map "\C-c\C-d" 'message-dont-send)
1315
1316   (define-key message-mode-map "\C-c\C-e" 'message-elide-region)
1317   (define-key message-mode-map "\C-c\C-v" 'message-delete-not-region)
1318   (define-key message-mode-map "\C-c\C-z" 'message-kill-to-signature)
1319   (define-key message-mode-map "\M-\r" 'message-newline-and-reformat)
1320
1321   (define-key message-mode-map "\C-c\C-a" 'mml-attach-file)
1322
1323   (define-key message-mode-map "\t" 'message-tab))
1324
1325 (easy-menu-define
1326  message-mode-menu message-mode-map "Message Menu."
1327  '("Message"
1328    ["Sort Headers" message-sort-headers t]
1329    ["Yank Original" message-yank-original t]
1330    ["Fill Yanked Message" message-fill-yanked-message t]
1331    ["Insert Signature" message-insert-signature t]
1332    ["Caesar (rot13) Message" message-caesar-buffer-body t]
1333    ["Caesar (rot13) Region" message-caesar-region (mark t)]
1334    ["Elide Region" message-elide-region (mark t)]
1335    ["Delete Outside Region" message-delete-not-region (mark t)]
1336    ["Kill To Signature" message-kill-to-signature t]
1337    ["Newline and Reformat" message-newline-and-reformat t]
1338    ["Rename buffer" message-rename-buffer t]
1339    ["Spellcheck" ispell-message t]
1340    ["Attach file as MIME" mml-attach-file t]
1341    "----"
1342    ["Send Message" message-send-and-exit t]
1343    ["Abort Message" message-dont-send t]
1344    ["Kill Message" message-kill-buffer t]))
1345
1346 (easy-menu-define
1347  message-mode-field-menu message-mode-map ""
1348  '("Field"
1349    ["Fetch To" message-insert-to t]
1350    ["Fetch Newsgroups" message-insert-newsgroups t]
1351    "----"
1352    ["To" message-goto-to t]
1353    ["Subject" message-goto-subject t]
1354    ["Cc" message-goto-cc t]
1355    ["Reply-To" message-goto-reply-to t]
1356    ["Summary" message-goto-summary t]
1357    ["Keywords" message-goto-keywords t]
1358    ["Newsgroups" message-goto-newsgroups t]
1359    ["Followup-To" message-goto-followup-to t]
1360    ["Distribution" message-goto-distribution t]
1361    ["Body" message-goto-body t]
1362    ["Signature" message-goto-signature t]))
1363
1364 (defvar facemenu-add-face-function)
1365 (defvar facemenu-remove-face-function)
1366
1367 ;;;###autoload
1368 (defun message-mode ()
1369   "Major mode for editing mail and news to be sent.
1370 Like Text Mode but with these additional commands:
1371 C-c C-s  message-send (send the message)    C-c C-c  message-send-and-exit
1372 C-c C-d  Pospone sending the message        C-c C-k  Kill the message
1373 C-c C-f  move to a header field (and create it if there isn't):
1374          C-c C-f C-t  move to To        C-c C-f C-s  move to Subject
1375          C-c C-f C-c  move to Cc        C-c C-f C-b  move to Bcc
1376          C-c C-f C-w  move to Fcc       C-c C-f C-r  move to Reply-To
1377          C-c C-f C-u  move to Summary   C-c C-f C-n  move to Newsgroups
1378          C-c C-f C-k  move to Keywords  C-c C-f C-d  move to Distribution
1379          C-c C-f C-f  move to Followup-To
1380 C-c C-t  message-insert-to (add a To header to a news followup)
1381 C-c C-n  message-insert-newsgroups (add a Newsgroup header to a news reply)
1382 C-c C-b  message-goto-body (move to beginning of message text).
1383 C-c C-i  message-goto-signature (move to the beginning of the signature).
1384 C-c C-w  message-insert-signature (insert `message-signature-file' file).
1385 C-c C-y  message-yank-original (insert current message, if any).
1386 C-c C-q  message-fill-yanked-message (fill what was yanked).
1387 C-c C-e  message-elide-region (elide the text between point and mark).
1388 C-c C-v  message-delete-not-region (remove the text outside the region).
1389 C-c C-z  message-kill-to-signature (kill the text up to the signature).
1390 C-c C-r  message-caesar-buffer-body (rot13 the message body).
1391 C-c C-a  mml-attach-file (attach a file as MIME).
1392 M-RET    message-newline-and-reformat (break the line and reformat)."
1393   (interactive)
1394   (kill-all-local-variables)
1395   (set (make-local-variable 'message-reply-buffer) nil)
1396   (make-local-variable 'message-send-actions)
1397   (make-local-variable 'message-exit-actions)
1398   (make-local-variable 'message-kill-actions)
1399   (make-local-variable 'message-postpone-actions)
1400   (make-local-variable 'message-draft-article)
1401   (make-local-hook 'kill-buffer-hook)
1402   (set-syntax-table message-mode-syntax-table)
1403   (use-local-map message-mode-map)
1404   (setq local-abbrev-table message-mode-abbrev-table)
1405   (setq major-mode 'message-mode)
1406   (setq mode-name "Message")
1407   (setq buffer-offer-save t)
1408   (make-local-variable 'facemenu-add-face-function)
1409   (make-local-variable 'facemenu-remove-face-function)
1410   (setq facemenu-add-face-function
1411         (lambda (face end)
1412           (let ((face-fun (cdr (assq face message-face-alist))))
1413             (if face-fun
1414                 (funcall face-fun (point) end)
1415               (error "Face %s not configured for %s mode" face mode-name)))
1416           "")
1417         facemenu-remove-face-function t)
1418   (make-local-variable 'paragraph-separate)
1419   (make-local-variable 'paragraph-start)
1420   ;; `-- ' precedes the signature.  `-----' appears at the start of the
1421   ;; lines that delimit forwarded messages.
1422   ;; Lines containing just >= 3 dashes, perhaps after whitespace,
1423   ;; are also sometimes used and should be separators.
1424   (setq paragraph-start
1425         (concat (regexp-quote mail-header-separator)
1426                 "$\\|[ \t]*[a-z0-9A-Z]*>+[ \t]*$\\|[ \t]*$\\|"
1427                 "-- $\\|---+$\\|"
1428                 page-delimiter
1429                 ;;!!! Uhm... shurely this can't be right?
1430                 "[> " (regexp-quote message-yank-prefix) "]+$"))
1431   (setq paragraph-separate paragraph-start)
1432   (make-local-variable 'message-reply-headers)
1433   (setq message-reply-headers nil)
1434   (make-local-variable 'message-newsreader)
1435   (make-local-variable 'message-mailer)
1436   (make-local-variable 'message-post-method)
1437   (set (make-local-variable 'message-sent-message-via) nil)
1438   (set (make-local-variable 'message-checksum) nil)
1439   (set (make-local-variable 'message-mime-part) 0)
1440   ;;(when (fboundp 'mail-hist-define-keys)
1441   ;;  (mail-hist-define-keys))
1442   (when (string-match "XEmacs\\|Lucid" emacs-version)
1443     (message-setup-toolbar))
1444   (easy-menu-add message-mode-menu message-mode-map)
1445   (easy-menu-add message-mode-field-menu message-mode-map)
1446   ;; Allow mail alias things.
1447   (when (eq message-mail-alias-type 'abbrev)
1448     (if (fboundp 'mail-abbrevs-setup)
1449         (mail-abbrevs-setup)
1450       (mail-aliases-setup)))
1451   (message-set-auto-save-file-name)
1452   (unless (string-match "XEmacs" emacs-version)
1453     (set (make-local-variable 'font-lock-defaults)
1454          '(message-font-lock-keywords t)))
1455   (make-local-variable 'adaptive-fill-regexp)
1456   (setq adaptive-fill-regexp
1457         (concat "[ \t]*[-a-z0-9A-Z]*\\(>[ \t]*\\)+[ \t]*\\|" adaptive-fill-regexp))
1458   (unless (boundp 'adaptive-fill-first-line-regexp)
1459     (setq adaptive-fill-first-line-regexp nil))
1460   (make-local-variable 'adaptive-fill-first-line-regexp)
1461   (setq adaptive-fill-first-line-regexp
1462         (concat "[ \t]*[-a-z0-9A-Z]*\\(>[ \t]*\\)+[ \t]*\\|"
1463                 adaptive-fill-first-line-regexp))
1464   (mm-enable-multibyte)
1465   (make-local-variable 'indent-tabs-mode) ;Turn off tabs for indentation.
1466   (setq indent-tabs-mode nil)
1467   (mml-mode)
1468   (run-hooks 'text-mode-hook 'message-mode-hook))
1469
1470 \f
1471
1472 ;;;
1473 ;;; Message mode commands
1474 ;;;
1475
1476 ;;; Movement commands
1477
1478 (defun message-goto-to ()
1479   "Move point to the To header."
1480   (interactive)
1481   (message-position-on-field "To"))
1482
1483 (defun message-goto-subject ()
1484   "Move point to the Subject header."
1485   (interactive)
1486   (message-position-on-field "Subject"))
1487
1488 (defun message-goto-cc ()
1489   "Move point to the Cc header."
1490   (interactive)
1491   (message-position-on-field "Cc" "To"))
1492
1493 (defun message-goto-bcc ()
1494   "Move point to the Bcc  header."
1495   (interactive)
1496   (message-position-on-field "Bcc" "Cc" "To"))
1497
1498 (defun message-goto-fcc ()
1499   "Move point to the Fcc header."
1500   (interactive)
1501   (message-position-on-field "Fcc" "To" "Newsgroups"))
1502
1503 (defun message-goto-reply-to ()
1504   "Move point to the Reply-To header."
1505   (interactive)
1506   (message-position-on-field "Reply-To" "Subject"))
1507
1508 (defun message-goto-newsgroups ()
1509   "Move point to the Newsgroups header."
1510   (interactive)
1511   (message-position-on-field "Newsgroups"))
1512
1513 (defun message-goto-distribution ()
1514   "Move point to the Distribution header."
1515   (interactive)
1516   (message-position-on-field "Distribution"))
1517
1518 (defun message-goto-followup-to ()
1519   "Move point to the Followup-To header."
1520   (interactive)
1521   (message-position-on-field "Followup-To" "Newsgroups"))
1522
1523 (defun message-goto-keywords ()
1524   "Move point to the Keywords header."
1525   (interactive)
1526   (message-position-on-field "Keywords" "Subject"))
1527
1528 (defun message-goto-summary ()
1529   "Move point to the Summary header."
1530   (interactive)
1531   (message-position-on-field "Summary" "Subject"))
1532
1533 (defun message-goto-body ()
1534   "Move point to the beginning of the message body."
1535   (interactive)
1536   (if (looking-at "[ \t]*\n") (expand-abbrev))
1537   (goto-char (point-min))
1538   (or (search-forward (concat "\n" mail-header-separator "\n") nil t)
1539       (search-forward "\n\n" nil t)))
1540
1541 (defun message-goto-eoh ()
1542   "Move point to the end of the headers."
1543   (interactive)
1544   (message-goto-body)
1545   (forward-line -1))
1546
1547 (defun message-goto-signature ()
1548   "Move point to the beginning of the message signature.
1549 If there is no signature in the article, go to the end and
1550 return nil."
1551   (interactive)
1552   (goto-char (point-min))
1553   (if (re-search-forward message-signature-separator nil t)
1554       (forward-line 1)
1555     (goto-char (point-max))
1556     nil))
1557
1558 \f
1559
1560 (defun message-insert-to (&optional force)
1561   "Insert a To header that points to the author of the article being replied to.
1562 If the original author requested not to be sent mail, the function signals
1563 an error.
1564 With the prefix argument FORCE, insert the header anyway."
1565   (interactive "P")
1566   (let ((co (message-fetch-reply-field "mail-copies-to")))
1567     (when (and (null force)
1568                co
1569                (or (equal (downcase co) "never")
1570                    (equal (downcase co) "nobody")))
1571       (error "The user has requested not to have copies sent via mail")))
1572   (when (and (message-position-on-field "To")
1573              (mail-fetch-field "to")
1574              (not (string-match "\\` *\\'" (mail-fetch-field "to"))))
1575     (insert ", "))
1576   (insert (or (message-fetch-reply-field "reply-to")
1577               (message-fetch-reply-field "from") "")))
1578
1579 (defun message-insert-newsgroups ()
1580   "Insert the Newsgroups header from the article being replied to."
1581   (interactive)
1582   (when (and (message-position-on-field "Newsgroups")
1583              (mail-fetch-field "newsgroups")
1584              (not (string-match "\\` *\\'" (mail-fetch-field "newsgroups"))))
1585     (insert ","))
1586   (insert (or (message-fetch-reply-field "newsgroups") "")))
1587
1588 \f
1589
1590 ;;; Various commands
1591
1592 (defun message-delete-not-region (beg end)
1593   "Delete everything in the body of the current message that is outside of the region."
1594   (interactive "r")
1595   (save-excursion
1596     (goto-char end)
1597     (delete-region (point) (if (not (message-goto-signature))
1598                                (point)
1599                              (forward-line -2)
1600                              (point)))
1601     (insert "\n")
1602     (goto-char beg)
1603     (delete-region beg (progn (message-goto-body)
1604                               (forward-line 2)
1605                               (point))))
1606   (when (message-goto-signature)
1607     (forward-line -2)))
1608
1609 (defun message-kill-to-signature ()
1610   "Deletes all text up to the signature."
1611   (interactive)
1612   (let ((point (point)))
1613     (message-goto-signature)
1614     (unless (eobp)
1615       (forward-line -2))
1616     (kill-region point (point))
1617     (unless (bolp)
1618       (insert "\n"))))
1619
1620 (defun message-newline-and-reformat ()
1621   "Insert four newlines, and then reformat if inside quoted text."
1622   (interactive)
1623   (let ((prefix "[]>»|:}+ \t]*")
1624         (supercite-thing "[-._a-zA-Z0-9]*[>]+[ \t]*")
1625         quoted point)
1626     (unless (bolp)
1627       (save-excursion
1628         (beginning-of-line)
1629         (when (looking-at (concat prefix
1630                                   supercite-thing))
1631           (setq quoted (match-string 0))))
1632       (insert "\n"))
1633     (setq point (point))
1634     (insert "\n\n\n")
1635     (delete-region (point) (re-search-forward "[ \t]*"))
1636     (when quoted
1637       (insert quoted))
1638     (fill-paragraph nil)
1639     (goto-char point)
1640     (forward-line 1)))
1641
1642 (defun message-insert-signature (&optional force)
1643   "Insert a signature.  See documentation for the `message-signature' variable."
1644   (interactive (list 0))
1645   (let* ((signature
1646           (cond
1647            ((and (null message-signature)
1648                  (eq force 0))
1649             (save-excursion
1650               (goto-char (point-max))
1651               (not (re-search-backward message-signature-separator nil t))))
1652            ((and (null message-signature)
1653                  force)
1654             t)
1655            ((message-functionp message-signature)
1656             (funcall message-signature))
1657            ((listp message-signature)
1658             (eval message-signature))
1659            (t message-signature)))
1660          (signature
1661           (cond ((stringp signature)
1662                  signature)
1663                 ((and (eq t signature)
1664                       message-signature-file
1665                       (file-exists-p message-signature-file))
1666                  signature))))
1667     (when signature
1668       (goto-char (point-max))
1669       ;; Insert the signature.
1670       (unless (bolp)
1671         (insert "\n"))
1672       (insert "\n-- \n")
1673       (if (eq signature t)
1674           (insert-file-contents message-signature-file)
1675         (insert signature))
1676       (goto-char (point-max))
1677       (or (bolp) (insert "\n")))))
1678
1679 (defun message-elide-region (b e)
1680   "Elide the text between point and mark.
1681 An ellipsis (from `message-elide-ellipsis') will be inserted where the
1682 text was killed."
1683   (interactive "r")
1684   (kill-region b e)
1685   (insert message-elide-ellipsis))
1686
1687 (defvar message-caesar-translation-table nil)
1688
1689 (defun message-caesar-region (b e &optional n)
1690   "Caesar rotation of region by N, default 13, for decrypting netnews."
1691   (interactive
1692    (list
1693     (min (point) (or (mark t) (point)))
1694     (max (point) (or (mark t) (point)))
1695     (when current-prefix-arg
1696       (prefix-numeric-value current-prefix-arg))))
1697
1698   (setq n (if (numberp n) (mod n 26) 13)) ;canonize N
1699   (unless (or (zerop n)                 ; no action needed for a rot of 0
1700               (= b e))                  ; no region to rotate
1701     ;; We build the table, if necessary.
1702     (when (or (not message-caesar-translation-table)
1703               (/= (aref message-caesar-translation-table ?a) (+ ?a n)))
1704         (setq message-caesar-translation-table
1705               (message-make-caesar-translation-table n)))
1706     ;; Then we translate the region.  Do it this way to retain
1707     ;; text properties.
1708     (while (< b e)
1709       (when (< (char-after b) 255)
1710         (subst-char-in-region
1711          b (1+ b) (char-after b)
1712          (aref message-caesar-translation-table (char-after b))))
1713       (incf b))))
1714
1715 (defun message-make-caesar-translation-table (n)
1716   "Create a rot table with offset N."
1717   (let ((i -1)
1718         (table (make-string 256 0)))
1719     (while (< (incf i) 256)
1720       (aset table i i))
1721     (concat
1722      (substring table 0 ?A)
1723      (substring table (+ ?A n) (+ ?A n (- 26 n)))
1724      (substring table ?A (+ ?A n))
1725      (substring table (+ ?A 26) ?a)
1726      (substring table (+ ?a n) (+ ?a n (- 26 n)))
1727      (substring table ?a (+ ?a n))
1728      (substring table (+ ?a 26) 255))))
1729
1730 (defun message-caesar-buffer-body (&optional rotnum)
1731   "Caesar rotates all letters in the current buffer by 13 places.
1732 Used to encode/decode possiblyun offensive messages (commonly in net.jokes).
1733 With prefix arg, specifies the number of places to rotate each letter forward.
1734 Mail and USENET news headers are not rotated."
1735   (interactive (if current-prefix-arg
1736                    (list (prefix-numeric-value current-prefix-arg))
1737                  (list nil)))
1738   (save-excursion
1739     (save-restriction
1740       (when (message-goto-body)
1741         (narrow-to-region (point) (point-max)))
1742       (message-caesar-region (point-min) (point-max) rotnum))))
1743
1744 (defun message-pipe-buffer-body (program)
1745   "Pipe the message body in the current buffer through PROGRAM."
1746   (save-excursion
1747     (save-restriction
1748       (when (message-goto-body)
1749         (narrow-to-region (point) (point-max)))
1750       (let ((body (buffer-substring (point-min) (point-max))))
1751         (unless (equal 0 (call-process-region
1752                            (point-min) (point-max) program t t))
1753             (insert body)
1754             (message "%s failed" program))))))
1755
1756 (defun message-rename-buffer (&optional enter-string)
1757   "Rename the *message* buffer to \"*message* RECIPIENT\".
1758 If the function is run with a prefix, it will ask for a new buffer
1759 name, rather than giving an automatic name."
1760   (interactive "Pbuffer name: ")
1761   (save-excursion
1762     (save-restriction
1763       (goto-char (point-min))
1764       (narrow-to-region (point)
1765                         (search-forward mail-header-separator nil 'end))
1766       (let* ((mail-to (or
1767                        (if (message-news-p) (message-fetch-field "Newsgroups")
1768                          (message-fetch-field "To"))
1769                        ""))
1770              (mail-trimmed-to
1771               (if (string-match "," mail-to)
1772                   (concat (substring mail-to 0 (match-beginning 0)) ", ...")
1773                 mail-to))
1774              (name-default (concat "*message* " mail-trimmed-to))
1775              (name (if enter-string
1776                        (read-string "New buffer name: " name-default)
1777                      name-default)))
1778         (rename-buffer name t)))))
1779
1780 (defun message-fill-yanked-message (&optional justifyp)
1781   "Fill the paragraphs of a message yanked into this one.
1782 Numeric argument means justify as well."
1783   (interactive "P")
1784   (save-excursion
1785     (goto-char (point-min))
1786     (search-forward (concat "\n" mail-header-separator "\n") nil t)
1787     (let ((fill-prefix message-yank-prefix))
1788       (fill-individual-paragraphs (point) (point-max) justifyp))))
1789
1790 (defun message-indent-citation ()
1791   "Modify text just inserted from a message to be cited.
1792 The inserted text should be the region.
1793 When this function returns, the region is again around the modified text.
1794
1795 Normally, indent each nonblank line `message-indentation-spaces' spaces.
1796 However, if `message-yank-prefix' is non-nil, insert that prefix on each line."
1797   (let ((start (point)))
1798     ;; Remove unwanted headers.
1799     (when message-ignored-cited-headers
1800       (let (all-removed)
1801         (save-restriction
1802           (narrow-to-region
1803            (goto-char start)
1804            (if (search-forward "\n\n" nil t)
1805                (1- (point))
1806              (point)))
1807           (message-remove-header message-ignored-cited-headers t)
1808           (when (= (point-min) (point-max))
1809             (setq all-removed t))
1810           (goto-char (point-max)))
1811         (if all-removed
1812             (goto-char start)
1813           (forward-line 1))))
1814     ;; Delete blank lines at the start of the buffer.
1815     (while (and (point-min)
1816                 (eolp)
1817                 (not (eobp)))
1818       (message-delete-line))
1819     ;; Delete blank lines at the end of the buffer.
1820     (goto-char (point-max))
1821     (unless (eolp)
1822       (insert "\n"))
1823     (while (and (zerop (forward-line -1))
1824                 (looking-at "$"))
1825       (message-delete-line))
1826     ;; Do the indentation.
1827     (if (null message-yank-prefix)
1828         (indent-rigidly start (mark t) message-indentation-spaces)
1829       (save-excursion
1830         (goto-char start)
1831         (while (< (point) (mark t))
1832           (insert message-yank-prefix)
1833           (forward-line 1))))
1834     (goto-char start)))
1835
1836 (defun message-yank-original (&optional arg)
1837   "Insert the message being replied to, if any.
1838 Puts point before the text and mark after.
1839 Normally indents each nonblank line ARG spaces (default 3).  However,
1840 if `message-yank-prefix' is non-nil, insert that prefix on each line.
1841
1842 This function uses `message-cite-function' to do the actual citing.
1843
1844 Just \\[universal-argument] as argument means don't indent, insert no
1845 prefix, and don't delete any headers."
1846   (interactive "P")
1847   (let ((modified (buffer-modified-p)))
1848     (when (and message-reply-buffer
1849                message-cite-function)
1850       (delete-windows-on message-reply-buffer t)
1851       (insert-buffer message-reply-buffer)
1852       (funcall message-cite-function)
1853       (message-exchange-point-and-mark)
1854       (unless (bolp)
1855         (insert ?\n))
1856       (unless modified
1857         (setq message-checksum (message-checksum))))))
1858
1859 (defun message-yank-buffer (buffer)
1860   "Insert BUFFER into the current buffer and quote it."
1861   (interactive "bYank buffer: ")
1862   (let ((message-reply-buffer buffer))
1863     (save-window-excursion
1864       (message-yank-original))))
1865
1866 (defun message-buffers ()
1867   "Return a list of active message buffers."
1868   (let (buffers)
1869     (save-excursion
1870       (dolist (buffer (buffer-list t))
1871         (set-buffer buffer)
1872         (when (and (eq major-mode 'message-mode)
1873                    (null message-sent-message-via))
1874           (push (buffer-name buffer) buffers))))
1875     (nreverse buffers)))
1876
1877 (defun message-cite-original-without-signature ()
1878   "Cite function in the standard Message manner."
1879   (let ((start (point))
1880         (end (mark t))
1881         (functions
1882          (when message-indent-citation-function
1883            (if (listp message-indent-citation-function)
1884                message-indent-citation-function
1885              (list message-indent-citation-function)))))
1886     (mml-quote-region start end)
1887     (goto-char end)
1888     (when (re-search-backward message-signature-separator start t)
1889       ;; Also peel off any blank lines before the signature.
1890       (forward-line -1)
1891       (while (looking-at "^[ \t]*$")
1892         (forward-line -1))
1893       (forward-line 1)
1894       (delete-region (point) end))
1895     (goto-char start)
1896     (while functions
1897       (funcall (pop functions)))
1898     (when message-citation-line-function
1899       (unless (bolp)
1900         (insert "\n"))
1901       (funcall message-citation-line-function))))
1902
1903 (defvar mail-citation-hook)             ;Compiler directive
1904 (defun message-cite-original ()
1905   "Cite function in the standard Message manner."
1906   (if (and (boundp 'mail-citation-hook)
1907            mail-citation-hook)
1908       (run-hooks 'mail-citation-hook)
1909     (let ((start (point))
1910           (end (mark t))
1911           (functions
1912            (when message-indent-citation-function
1913              (if (listp message-indent-citation-function)
1914                  message-indent-citation-function
1915                (list message-indent-citation-function)))))
1916       (mml-quote-region start end)
1917       (goto-char start)
1918       (while functions
1919         (funcall (pop functions)))
1920       (when message-citation-line-function
1921         (unless (bolp)
1922           (insert "\n"))
1923         (funcall message-citation-line-function)))))
1924
1925 (defun message-insert-citation-line ()
1926   "Function that inserts a simple citation line."
1927   (when message-reply-headers
1928     (insert (mail-header-from message-reply-headers) " writes:\n\n")))
1929
1930 (defun message-position-on-field (header &rest afters)
1931   (let ((case-fold-search t))
1932     (save-restriction
1933       (narrow-to-region
1934        (goto-char (point-min))
1935        (progn
1936          (re-search-forward
1937           (concat "^" (regexp-quote mail-header-separator) "$"))
1938          (match-beginning 0)))
1939       (goto-char (point-min))
1940       (if (re-search-forward (concat "^" (regexp-quote header) ":") nil t)
1941           (progn
1942             (re-search-forward "^[^ \t]" nil 'move)
1943             (beginning-of-line)
1944             (skip-chars-backward "\n")
1945             t)
1946         (while (and afters
1947                     (not (re-search-forward
1948                           (concat "^" (regexp-quote (car afters)) ":")
1949                           nil t)))
1950           (pop afters))
1951         (when afters
1952           (re-search-forward "^[^ \t]" nil 'move)
1953           (beginning-of-line))
1954         (insert header ": \n")
1955         (forward-char -1)
1956         nil))))
1957
1958 (defun message-remove-signature ()
1959   "Remove the signature from the text between point and mark.
1960 The text will also be indented the normal way."
1961   (save-excursion
1962     (let ((start (point))
1963           mark)
1964       (if (not (re-search-forward message-signature-separator (mark t) t))
1965           ;; No signature here, so we just indent the cited text.
1966           (message-indent-citation)
1967         ;; Find the last non-empty line.
1968         (forward-line -1)
1969         (while (looking-at "[ \t]*$")
1970           (forward-line -1))
1971         (forward-line 1)
1972         (setq mark (set-marker (make-marker) (point)))
1973         (goto-char start)
1974         (message-indent-citation)
1975         ;; Enable undoing the deletion.
1976         (undo-boundary)
1977         (delete-region mark (mark t))
1978         (set-marker mark nil)))))
1979
1980 \f
1981
1982 ;;;
1983 ;;; Sending messages
1984 ;;;
1985
1986 (defun message-send-and-exit (&optional arg)
1987   "Send message like `message-send', then, if no errors, exit from mail buffer."
1988   (interactive "P")
1989   (let ((buf (current-buffer))
1990         (actions message-exit-actions))
1991     (when (and (message-send arg)
1992                (buffer-name buf))
1993       (if message-kill-buffer-on-exit
1994           (kill-buffer buf)
1995         (bury-buffer buf)
1996         (when (eq buf (current-buffer))
1997           (message-bury buf)))
1998       (message-do-actions actions)
1999       t)))
2000
2001 (defun message-dont-send ()
2002   "Don't send the message you have been editing."
2003   (interactive)
2004   (set-buffer-modified-p t)
2005   (save-buffer)
2006   (let ((actions message-postpone-actions))
2007     (message-bury (current-buffer))
2008     (message-do-actions actions)))
2009
2010 (defun message-kill-buffer ()
2011   "Kill the current buffer."
2012   (interactive)
2013   (when (or (not (buffer-modified-p))
2014             (yes-or-no-p "Message modified; kill anyway? "))
2015     (let ((actions message-kill-actions))
2016       (setq buffer-file-name nil)
2017       (kill-buffer (current-buffer))
2018       (message-do-actions actions))))
2019
2020 (defun message-bury (buffer)
2021   "Bury this mail buffer."
2022   (let ((newbuf (other-buffer buffer)))
2023     (bury-buffer buffer)
2024     (if (and (fboundp 'frame-parameters)
2025              (cdr (assq 'dedicated (frame-parameters)))
2026              (not (null (delq (selected-frame) (visible-frame-list)))))
2027         (delete-frame (selected-frame))
2028       (switch-to-buffer newbuf))))
2029
2030 (defun message-send (&optional arg)
2031   "Send the message in the current buffer.
2032 If `message-interactive' is non-nil, wait for success indication
2033 or error messages, and inform user.
2034 Otherwise any failure is reported in a message back to
2035 the user from the mailer."
2036   (interactive "P")
2037   ;; Make it possible to undo the coming changes.
2038   (undo-boundary)
2039   (let ((inhibit-read-only t))
2040     (put-text-property (point-min) (point-max) 'read-only nil))
2041   (message-fix-before-sending)
2042   (run-hooks 'message-send-hook)
2043   (message "Sending...")
2044   (let ((alist message-send-method-alist)
2045         (success t)
2046         elem sent)
2047     (while (and success
2048                 (setq elem (pop alist)))
2049       (when (or (not (funcall (cadr elem)))
2050                 (and (or (not (memq (car elem)
2051                                     message-sent-message-via))
2052                          (y-or-n-p
2053                           (format
2054                            "Already sent message via %s; resend? "
2055                            (car elem))))
2056                      (setq success (funcall (caddr elem) arg))))
2057         (setq sent t)))
2058     (unless (or sent (not success))
2059       (error "No methods specified to send by"))
2060     (when (and success sent)
2061       (message-do-fcc)
2062       (save-excursion
2063         (run-hooks 'message-sent-hook))
2064       (message "Sending...done")
2065       ;; Mark the buffer as unmodified and delete auto-save.
2066       (set-buffer-modified-p nil)
2067       (delete-auto-save-file-if-necessary t)
2068       (message-disassociate-draft)
2069       ;; Delete other mail buffers and stuff.
2070       (message-do-send-housekeeping)
2071       (message-do-actions message-send-actions)
2072       ;; Return success.
2073       t)))
2074
2075 (defun message-send-via-mail (arg)
2076   "Send the current message via mail."
2077   (message-send-mail arg))
2078
2079 (defun message-send-via-news (arg)
2080   "Send the current message via news."
2081   (funcall message-send-news-function arg))
2082
2083 (defmacro message-check (type &rest forms)
2084   "Eval FORMS if TYPE is to be checked."
2085   `(or (message-check-element ,type)
2086        (save-excursion
2087          ,@forms)))
2088
2089 (put 'message-check 'lisp-indent-function 1)
2090 (put 'message-check 'edebug-form-spec '(form body))
2091
2092 (defun message-fix-before-sending ()
2093   "Do various things to make the message nice before sending it."
2094   ;; Make sure there's a newline at the end of the message.
2095   (goto-char (point-max))
2096   (unless (bolp)
2097     (insert "\n"))
2098   ;; Delete all invisible text.
2099   (message-check 'invisible-text
2100     (when (text-property-any (point-min) (point-max) 'invisible t)
2101       (put-text-property (point-min) (point-max) 'invisible nil)
2102       (unless (yes-or-no-p
2103                "Invisible text found and made visible; continue posting? ")
2104         (error "Invisible text found and made visible")))))
2105
2106 (defun message-add-action (action &rest types)
2107   "Add ACTION to be performed when doing an exit of type TYPES."
2108   (let (var)
2109     (while types
2110       (set (setq var (intern (format "message-%s-actions" (pop types))))
2111            (nconc (symbol-value var) (list action))))))
2112
2113 (defun message-do-actions (actions)
2114   "Perform all actions in ACTIONS."
2115   ;; Now perform actions on successful sending.
2116   (while actions
2117     (ignore-errors
2118       (cond
2119        ;; A simple function.
2120        ((message-functionp (car actions))
2121         (funcall (car actions)))
2122        ;; Something to be evaled.
2123        (t
2124         (eval (car actions)))))
2125     (pop actions)))
2126
2127 (defun message-send-mail (&optional arg)
2128   (require 'mail-utils)
2129   (let ((tembuf (message-generate-new-buffer-clone-locals " message temp"))
2130         (case-fold-search nil)
2131         (news (message-news-p))
2132         (mailbuf (current-buffer)))
2133     (save-restriction
2134       (message-narrow-to-headers)
2135       ;; Insert some headers.
2136       (let ((message-deletable-headers
2137              (if news nil message-deletable-headers)))
2138         (message-generate-headers message-required-mail-headers))
2139       ;; Let the user do all of the above.
2140       (run-hooks 'message-header-hook))
2141     (unwind-protect
2142         (save-excursion
2143           (set-buffer tembuf)
2144           (erase-buffer)
2145           ;; Avoid copying text props.
2146           (insert (format
2147                    "%s" (save-excursion
2148                           (set-buffer mailbuf)
2149                           (buffer-string))))
2150           ;; Remove some headers.
2151           (message-encode-message-body)
2152           (save-restriction
2153             (message-narrow-to-headers)
2154             ;; We (re)generate the Lines header.
2155             (when (memq 'Lines message-required-mail-headers)
2156               (message-generate-headers '(Lines)))
2157             ;; Remove some headers.
2158             (message-remove-header message-ignored-mail-headers t)
2159             (mail-encode-encoded-word-buffer))
2160           (goto-char (point-max))
2161           ;; require one newline at the end.
2162           (or (= (preceding-char) ?\n)
2163               (insert ?\n))
2164           (when (and news
2165                      (or (message-fetch-field "cc")
2166                          (message-fetch-field "to")))
2167             (message-insert-courtesy-copy))
2168           (funcall message-send-mail-function))
2169       (kill-buffer tembuf))
2170     (set-buffer mailbuf)
2171     (push 'mail message-sent-message-via)))
2172
2173 (defun message-send-mail-with-sendmail ()
2174   "Send off the prepared buffer with sendmail."
2175   (let ((errbuf (if message-interactive
2176                     (generate-new-buffer " sendmail errors")
2177                   0))
2178         resend-to-addresses delimline)
2179     (let ((case-fold-search t))
2180       (save-restriction
2181         (message-narrow-to-headers)
2182         (setq resend-to-addresses (message-fetch-field "resent-to")))
2183       ;; Change header-delimiter to be what sendmail expects.
2184       (goto-char (point-min))
2185       (re-search-forward
2186        (concat "^" (regexp-quote mail-header-separator) "\n"))
2187       (replace-match "\n")
2188       (backward-char 1)
2189       (setq delimline (point-marker))
2190       (run-hooks 'message-send-mail-hook)
2191       ;; Insert an extra newline if we need it to work around
2192       ;; Sun's bug that swallows newlines.
2193       (goto-char (1+ delimline))
2194       (when (eval message-mailer-swallows-blank-line)
2195         (newline))
2196       (when message-interactive
2197         (save-excursion
2198           (set-buffer errbuf)
2199           (erase-buffer))))
2200     (let ((default-directory "/")
2201           (coding-system-for-write message-send-coding-system))
2202       (apply 'call-process-region
2203              (append (list (point-min) (point-max)
2204                            (if (boundp 'sendmail-program)
2205                                sendmail-program
2206                              "/usr/lib/sendmail")
2207                            nil errbuf nil "-oi")
2208                      ;; Always specify who from,
2209                      ;; since some systems have broken sendmails.
2210                      ;; But some systems are more broken with -f, so
2211                      ;; we'll let users override this.
2212                      (if (null message-sendmail-f-is-evil)
2213                          (list "-f" (user-login-name)))
2214                      ;; These mean "report errors by mail"
2215                      ;; and "deliver in background".
2216                      (if (null message-interactive) '("-oem" "-odb"))
2217                      ;; Get the addresses from the message
2218                      ;; unless this is a resend.
2219                      ;; We must not do that for a resend
2220                      ;; because we would find the original addresses.
2221                      ;; For a resend, include the specific addresses.
2222                      (if resend-to-addresses
2223                          (list resend-to-addresses)
2224                        '("-t")))))
2225     (when message-interactive
2226       (save-excursion
2227         (set-buffer errbuf)
2228         (goto-char (point-min))
2229         (while (re-search-forward "\n\n* *" nil t)
2230           (replace-match "; "))
2231         (if (not (zerop (buffer-size)))
2232             (error "Sending...failed to %s"
2233                    (buffer-substring (point-min) (point-max)))))
2234       (when (bufferp errbuf)
2235         (kill-buffer errbuf)))))
2236
2237 (defun message-send-mail-with-qmail ()
2238   "Pass the prepared message buffer to qmail-inject.
2239 Refer to the documentation for the variable `message-send-mail-function'
2240 to find out how to use this."
2241   ;; replace the header delimiter with a blank line
2242   (goto-char (point-min))
2243   (re-search-forward
2244    (concat "^" (regexp-quote mail-header-separator) "\n"))
2245   (replace-match "\n")
2246   (run-hooks 'message-send-mail-hook)
2247   ;; send the message
2248   (case
2249       (let ((coding-system-for-write message-send-coding-system))
2250         (apply
2251          'call-process-region 1 (point-max) message-qmail-inject-program
2252          nil nil nil
2253          ;; qmail-inject's default behaviour is to look for addresses on the
2254          ;; command line; if there're none, it scans the headers.
2255          ;; yes, it does The Right Thing w.r.t. Resent-To and it's kin.
2256          ;;
2257          ;; in general, ALL of qmail-inject's defaults are perfect for simply
2258          ;; reading a formatted (i. e., at least a To: or Resent-To header)
2259          ;; message from stdin.
2260          ;;
2261          ;; qmail also has the advantage of not having been raped by
2262          ;; various vendors, so we don't have to allow for that, either --
2263          ;; compare this with message-send-mail-with-sendmail and weep
2264          ;; for sendmail's lost innocence.
2265          ;;
2266          ;; all this is way cool coz it lets us keep the arguments entirely
2267          ;; free for -inject-arguments -- a big win for the user and for us
2268          ;; since we don't have to play that double-guessing game and the user
2269          ;; gets full control (no gestapo'ish -f's, for instance).  --sj
2270          message-qmail-inject-args))
2271     ;; qmail-inject doesn't say anything on it's stdout/stderr,
2272     ;; we have to look at the retval instead
2273     (0 nil)
2274     (1   (error "qmail-inject reported permanent failure"))
2275     (111 (error "qmail-inject reported transient failure"))
2276     ;; should never happen
2277     (t   (error "qmail-inject reported unknown failure"))))
2278
2279 (defun message-send-mail-with-mh ()
2280   "Send the prepared message buffer with mh."
2281   (let ((mh-previous-window-config nil)
2282         (name (mh-new-draft-name)))
2283     (setq buffer-file-name name)
2284     ;; MH wants to generate these headers itself.
2285     (when message-mh-deletable-headers
2286       (let ((headers message-mh-deletable-headers))
2287         (while headers
2288           (goto-char (point-min))
2289           (and (re-search-forward
2290                 (concat "^" (symbol-name (car headers)) ": *") nil t)
2291                (message-delete-line))
2292           (pop headers))))
2293     (run-hooks 'message-send-mail-hook)
2294     ;; Pass it on to mh.
2295     (mh-send-letter)))
2296
2297 (defun message-send-news (&optional arg)
2298   (let ((tembuf (message-generate-new-buffer-clone-locals " *message temp*"))
2299         (case-fold-search nil)
2300         (method (if (message-functionp message-post-method)
2301                     (funcall message-post-method arg)
2302                   message-post-method))
2303         (messbuf (current-buffer))
2304         (message-syntax-checks
2305          (if arg
2306              (cons '(existing-newsgroups . disabled)
2307                    message-syntax-checks)
2308            message-syntax-checks))
2309         result)
2310     (if (not (message-check-news-body-syntax))
2311         nil
2312       (save-restriction
2313         (message-narrow-to-headers)
2314         ;; Insert some headers.
2315         (message-generate-headers message-required-news-headers)
2316         ;; Let the user do all of the above.
2317         (run-hooks 'message-header-hook))
2318       (message-cleanup-headers)
2319       (if (not (message-check-news-syntax))
2320           nil
2321         (unwind-protect
2322             (save-excursion
2323               (set-buffer tembuf)
2324               (buffer-disable-undo)
2325               (erase-buffer)
2326               ;; Avoid copying text props.
2327               (insert (format
2328                        "%s" (save-excursion
2329                               (set-buffer messbuf)
2330                               (buffer-string))))
2331               (message-encode-message-body)
2332               ;; Remove some headers.
2333               (save-restriction
2334                 (message-narrow-to-headers)
2335                 ;; We (re)generate the Lines header.
2336                 (when (memq 'Lines message-required-mail-headers)
2337                   (message-generate-headers '(Lines)))
2338                 ;; Remove some headers.
2339                 (message-remove-header message-ignored-news-headers t)
2340                 (let ((mail-parse-charset message-posting-charset))
2341                   (mail-encode-encoded-word-buffer)))
2342               (goto-char (point-max))
2343               ;; require one newline at the end.
2344               (or (= (preceding-char) ?\n)
2345                   (insert ?\n))
2346               (let ((case-fold-search t))
2347                 ;; Remove the delimiter.
2348                 (goto-char (point-min))
2349                 (re-search-forward
2350                  (concat "^" (regexp-quote mail-header-separator) "\n"))
2351                 (replace-match "\n")
2352                 (backward-char 1))
2353               (run-hooks 'message-send-news-hook)
2354               (gnus-open-server method)
2355             (setq result (let ((mail-header-separator ""))
2356                            (gnus-request-post method))))
2357           (kill-buffer tembuf))
2358         (set-buffer messbuf)
2359         (if result
2360             (push 'news message-sent-message-via)
2361           (message "Couldn't send message via news: %s"
2362                    (nnheader-get-report (car method)))
2363           nil)))))
2364
2365 ;;;
2366 ;;; Header generation & syntax checking.
2367 ;;;
2368
2369 (defun message-check-element (type)
2370   "Returns non-nil if this type is not to be checked."
2371   (if (eq message-syntax-checks 'dont-check-for-anything-just-trust-me)
2372       t
2373     (let ((able (assq type message-syntax-checks)))
2374       (and (consp able)
2375            (eq (cdr able) 'disabled)))))
2376
2377 (defun message-check-news-syntax ()
2378   "Check the syntax of the message."
2379   (save-excursion
2380     (save-restriction
2381       (widen)
2382       ;; We narrow to the headers and check them first.
2383       (save-excursion
2384         (save-restriction
2385           (message-narrow-to-headers)
2386           (message-check-news-header-syntax))))))
2387
2388 (defun message-check-news-header-syntax ()
2389   (and
2390    ;; Check Newsgroups header.
2391    (message-check 'newsgroyps
2392      (let ((group (message-fetch-field "newsgroups")))
2393        (or
2394         (and group
2395              (not (string-match "\\`[ \t]*\\'" group)))
2396         (ignore
2397          (message
2398           "The newsgroups field is empty or missing.  Posting is denied.")))))
2399    ;; Check the Subject header.
2400    (message-check 'subject
2401      (let* ((case-fold-search t)
2402             (subject (message-fetch-field "subject")))
2403        (or
2404         (and subject
2405              (not (string-match "\\`[ \t]*\\'" subject)))
2406         (ignore
2407          (message
2408           "The subject field is empty or missing.  Posting is denied.")))))
2409    ;; Check for commands in Subject.
2410    (message-check 'subject-cmsg
2411      (if (string-match "^cmsg " (message-fetch-field "subject"))
2412          (y-or-n-p
2413           "The control code \"cmsg\" is in the subject.  Really post? ")
2414        t))
2415    ;; Check for multiple identical headers.
2416    (message-check 'multiple-headers
2417      (let (found)
2418        (while (and (not found)
2419                    (re-search-forward "^[^ \t:]+: " nil t))
2420          (save-excursion
2421            (or (re-search-forward
2422                 (concat "^"
2423                         (regexp-quote
2424                          (setq found
2425                                (buffer-substring
2426                                 (match-beginning 0) (- (match-end 0) 2))))
2427                         ":")
2428                 nil t)
2429                (setq found nil))))
2430        (if found
2431            (y-or-n-p (format "Multiple %s headers.  Really post? " found))
2432          t)))
2433    ;; Check for Version and Sendsys.
2434    (message-check 'sendsys
2435      (if (re-search-forward "^Sendsys:\\|^Version:" nil t)
2436          (y-or-n-p
2437           (format "The article contains a %s command.  Really post? "
2438                   (buffer-substring (match-beginning 0)
2439                                     (1- (match-end 0)))))
2440        t))
2441    ;; See whether we can shorten Followup-To.
2442    (message-check 'shorten-followup-to
2443      (let ((newsgroups (message-fetch-field "newsgroups"))
2444            (followup-to (message-fetch-field "followup-to"))
2445            to)
2446        (when (and newsgroups
2447                   (string-match "," newsgroups)
2448                   (not followup-to)
2449                   (not
2450                    (zerop
2451                     (length
2452                      (setq to (completing-read
2453                                "Followups to: (default all groups) "
2454                                (mapcar (lambda (g) (list g))
2455                                        (cons "poster"
2456                                              (message-tokenize-header
2457                                               newsgroups)))))))))
2458          (goto-char (point-min))
2459          (insert "Followup-To: " to "\n"))
2460        t))
2461    ;; Check "Shoot me".
2462    (message-check 'shoot
2463      (if (re-search-forward
2464           "Message-ID.*.i-did-not-set--mail-host-address--so-shoot-me" nil t)
2465          (y-or-n-p "You appear to have a misconfigured system.  Really post? ")
2466        t))
2467    ;; Check for Approved.
2468    (message-check 'approved
2469      (if (re-search-forward "^Approved:" nil t)
2470          (y-or-n-p "The article contains an Approved header.  Really post? ")
2471        t))
2472    ;; Check the Message-ID header.
2473    (message-check 'message-id
2474      (let* ((case-fold-search t)
2475             (message-id (message-fetch-field "message-id" t)))
2476        (or (not message-id)
2477            ;; Is there an @ in the ID?
2478            (and (string-match "@" message-id)
2479                 ;; Is there a dot in the ID?
2480                 (string-match "@[^.]*\\." message-id)
2481                 ;; Does the ID end with a dot?
2482                 (not (string-match "\\.>" message-id)))
2483            (y-or-n-p
2484             (format "The Message-ID looks strange: \"%s\".  Really post? "
2485                     message-id)))))
2486    ;; Check the Newsgroups & Followup-To headers.
2487    (message-check 'existing-newsgroups
2488      (let* ((case-fold-search t)
2489             (newsgroups (message-fetch-field "newsgroups"))
2490             (followup-to (message-fetch-field "followup-to"))
2491             (groups (message-tokenize-header
2492                      (if followup-to
2493                          (concat newsgroups "," followup-to)
2494                        newsgroups)))
2495             (hashtb (and (boundp 'gnus-active-hashtb)
2496                          gnus-active-hashtb))
2497             errors)
2498        (if (or (not hashtb)
2499                (not (boundp 'gnus-read-active-file))
2500                (not gnus-read-active-file)
2501                (eq gnus-read-active-file 'some))
2502            t
2503          (while groups
2504            (when (and (not (boundp (intern (car groups) hashtb)))
2505                       (not (equal (car groups) "poster")))
2506              (push (car groups) errors))
2507            (pop groups))
2508          (if (not errors)
2509              t
2510            (y-or-n-p
2511             (format
2512              "Really post to %s unknown group%s: %s "
2513              (if (= (length errors) 1) "this" "these")
2514              (if (= (length errors) 1) "" "s")
2515              (mapconcat 'identity errors ", ")))))))
2516    ;; Check the Newsgroups & Followup-To headers for syntax errors.
2517    (message-check 'valid-newsgroups
2518      (let ((case-fold-search t)
2519            (headers '("Newsgroups" "Followup-To"))
2520            header error)
2521        (while (and headers (not error))
2522          (when (setq header (mail-fetch-field (car headers)))
2523            (if (or
2524                 (not
2525                  (string-match
2526                   "\\`\\([-+_&.a-zA-Z0-9]+\\)?\\(,[-+_&.a-zA-Z0-9]+\\)*\\'"
2527                   header))
2528                 (memq
2529                  nil (mapcar
2530                       (lambda (g)
2531                         (not (string-match "\\.\\'\\|\\.\\." g)))
2532                       (message-tokenize-header header ","))))
2533                (setq error t)))
2534          (unless error
2535            (pop headers)))
2536        (if (not error)
2537            t
2538          (y-or-n-p
2539           (format "The %s header looks odd: \"%s\".  Really post? "
2540                   (car headers) header)))))
2541    (message-check 'repeated-newsgroups
2542      (let ((case-fold-search t)
2543            (headers '("Newsgroups" "Followup-To"))
2544            header error groups group)
2545        (while (and headers
2546                    (not error))
2547          (when (setq header (mail-fetch-field (pop headers)))
2548            (setq groups (message-tokenize-header header ","))
2549            (while (setq group (pop groups))
2550              (when (member group groups)
2551                (setq error group
2552                      groups nil)))))
2553        (if (not error)
2554            t
2555          (y-or-n-p
2556           (format "Group %s is repeated in headers.  Really post? " error)))))
2557    ;; Check the From header.
2558    (message-check 'from
2559      (let* ((case-fold-search t)
2560             (from (message-fetch-field "from"))
2561             ad)
2562        (cond
2563         ((not from)
2564          (message "There is no From line.  Posting is denied.")
2565          nil)
2566         ((or (not (string-match
2567                    "@[^\\.]*\\."
2568                    (setq ad (nth 1 (mail-extract-address-components
2569                                     from))))) ;larsi@ifi
2570              (string-match "\\.\\." ad) ;larsi@ifi..uio
2571              (string-match "@\\." ad)   ;larsi@.ifi.uio
2572              (string-match "\\.$" ad)   ;larsi@ifi.uio.
2573              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
2574              (string-match "(.*).*(.*)" from)) ;(lars) (lars)
2575          (message
2576           "Denied posting -- the From looks strange: \"%s\"." from)
2577          nil)
2578         (t t))))))
2579
2580 (defun message-check-news-body-syntax ()
2581   (and
2582    ;; Check for long lines.
2583    (message-check 'long-lines
2584      (goto-char (point-min))
2585      (re-search-forward
2586       (concat "^" (regexp-quote mail-header-separator) "$"))
2587      (while (and
2588              (progn
2589                (end-of-line)
2590                (< (current-column) 80))
2591              (zerop (forward-line 1))))
2592      (or (bolp)
2593          (eobp)
2594          (y-or-n-p
2595           "You have lines longer than 79 characters.  Really post? ")))
2596    ;; Check whether the article is empty.
2597    (message-check 'empty
2598      (goto-char (point-min))
2599      (re-search-forward
2600       (concat "^" (regexp-quote mail-header-separator) "$"))
2601      (forward-line 1)
2602      (let ((b (point)))
2603        (goto-char (point-max))
2604        (re-search-backward message-signature-separator nil t)
2605        (beginning-of-line)
2606        (or (re-search-backward "[^ \n\t]" b t)
2607            (y-or-n-p "Empty article.  Really post? "))))
2608    ;; Check for control characters.
2609    (message-check 'control-chars
2610      (if (re-search-forward "[\000-\007\013\015-\032\034-\037\200-\237]" nil t)
2611          (y-or-n-p
2612           "The article contains control characters.  Really post? ")
2613        t))
2614    ;; Check excessive size.
2615    (message-check 'size
2616      (if (> (buffer-size) 60000)
2617          (y-or-n-p
2618           (format "The article is %d octets long.  Really post? "
2619                   (buffer-size)))
2620        t))
2621    ;; Check whether any new text has been added.
2622    (message-check 'new-text
2623      (or
2624       (not message-checksum)
2625       (not (eq (message-checksum) message-checksum))
2626       (y-or-n-p
2627        "It looks like no new text has been added.  Really post? ")))
2628    ;; Check the length of the signature.
2629    (message-check 'signature
2630      (goto-char (point-max))
2631      (if (> (count-lines (point) (point-max)) 5)
2632          (y-or-n-p
2633           (format
2634            "Your .sig is %d lines; it should be max 4.  Really post? "
2635            (1- (count-lines (point) (point-max)))))
2636        t))))
2637
2638 (defun message-checksum ()
2639   "Return a \"checksum\" for the current buffer."
2640   (let ((sum 0))
2641     (save-excursion
2642       (goto-char (point-min))
2643       (re-search-forward
2644        (concat "^" (regexp-quote mail-header-separator) "$"))
2645       (while (not (eobp))
2646         (when (not (looking-at "[ \t\n]"))
2647           (setq sum (logxor (ash sum 1) (if (natnump sum) 0 1)
2648                             (char-after))))
2649         (forward-char 1)))
2650     sum))
2651
2652 (defun message-do-fcc ()
2653   "Process Fcc headers in the current buffer."
2654   (let ((case-fold-search t)
2655         (buf (current-buffer))
2656         list file)
2657     (save-excursion
2658       (set-buffer (get-buffer-create " *message temp*"))
2659       (erase-buffer)
2660       (insert-buffer-substring buf)
2661       (save-restriction
2662         (message-narrow-to-headers)
2663         (while (setq file (message-fetch-field "fcc"))
2664           (push file list)
2665           (message-remove-header "fcc" nil t)))
2666       (goto-char (point-min))
2667       (re-search-forward (concat "^" (regexp-quote mail-header-separator) "$"))
2668       (replace-match "" t t)
2669       ;; Process FCC operations.
2670       (while list
2671         (setq file (pop list))
2672         (if (string-match "^[ \t]*|[ \t]*\\(.*\\)[ \t]*$" file)
2673             ;; Pipe the article to the program in question.
2674             (call-process-region (point-min) (point-max) shell-file-name
2675                                  nil nil nil shell-command-switch
2676                                  (match-string 1 file))
2677           ;; Save the article.
2678           (setq file (expand-file-name file))
2679           (unless (file-exists-p (file-name-directory file))
2680             (make-directory (file-name-directory file) t))
2681           (if (and message-fcc-handler-function
2682                    (not (eq message-fcc-handler-function 'rmail-output)))
2683               (funcall message-fcc-handler-function file)
2684             (if (and (file-readable-p file) (mail-file-babyl-p file))
2685                 (rmail-output file 1 nil t)
2686               (let ((mail-use-rfc822 t))
2687                 (rmail-output file 1 t t))))))
2688
2689       (kill-buffer (current-buffer)))))
2690
2691 (defun message-output (filename)
2692   "Append this article to Unix/babyl mail file.."
2693   (if (and (file-readable-p filename)
2694            (mail-file-babyl-p filename))
2695       (rmail-output-to-rmail-file filename t)
2696     (gnus-output-to-mail filename t)))
2697
2698 (defun message-cleanup-headers ()
2699   "Do various automatic cleanups of the headers."
2700   ;; Remove empty lines in the header.
2701   (save-restriction
2702     (message-narrow-to-headers)
2703     ;; Remove blank lines.
2704     (while (re-search-forward "^[ \t]*\n" nil t)
2705       (replace-match "" t t))
2706
2707     ;; Correct Newsgroups and Followup-To headers:  Change sequence of
2708     ;; spaces to comma and eliminate spaces around commas.  Eliminate
2709     ;; embedded line breaks.
2710     (goto-char (point-min))
2711     (while (re-search-forward "^\\(Newsgroups\\|Followup-To\\): +" nil t)
2712       (save-restriction
2713         (narrow-to-region
2714          (point)
2715          (if (re-search-forward "^[^ \t]" nil t)
2716              (match-beginning 0)
2717            (forward-line 1)
2718            (point)))
2719         (goto-char (point-min))
2720         (while (re-search-forward "\n[ \t]+" nil t)
2721           (replace-match " " t t))      ;No line breaks (too confusing)
2722         (goto-char (point-min))
2723         (while (re-search-forward "[ \t\n]*,[ \t\n]*\\|[ \t]+" nil t)
2724           (replace-match "," t t))
2725         (goto-char (point-min))
2726         ;; Remove trailing commas.
2727         (when (re-search-forward ",+$" nil t)
2728           (replace-match "" t t))))))
2729
2730 (defun message-make-date (&optional now)
2731   "Make a valid data header.
2732 If NOW, use that time instead."
2733   (let* ((now (or now (current-time)))
2734          (zone (nth 8 (decode-time now)))
2735          (sign "+"))
2736     (when (< zone 0)
2737       (setq sign "-")
2738       (setq zone (- zone)))
2739     (concat
2740      (format-time-string "%d" now)
2741      ;; The month name of the %b spec is locale-specific.  Pfff.
2742      (format " %s "
2743              (capitalize (car (rassoc (nth 4 (decode-time now))
2744                                       parse-time-months))))
2745      (format-time-string "%Y %H:%M:%S " now)
2746      ;; We do all of this because XEmacs doesn't have the %z spec.
2747      (format "%s%02d%02d" sign (/ zone 3600) (/ (% zone 3600) 60)))))
2748
2749 (defun message-make-message-id ()
2750   "Make a unique Message-ID."
2751   (concat "<" (message-unique-id)
2752           (let ((psubject (save-excursion (message-fetch-field "subject")))
2753                 (psupersedes
2754                  (save-excursion (message-fetch-field "supersedes"))))
2755             (if (or
2756                  (and message-reply-headers
2757                       (mail-header-references message-reply-headers)
2758                       (mail-header-subject message-reply-headers)
2759                       psubject
2760                       (mail-header-subject message-reply-headers)
2761                       (not (string=
2762                             (message-strip-subject-re
2763                              (mail-header-subject message-reply-headers))
2764                             (message-strip-subject-re psubject))))
2765                  (and psupersedes
2766                       (string-match "_-_@" psupersedes)))
2767                 "_-_" ""))
2768           "@" (message-make-fqdn) ">"))
2769
2770 (defvar message-unique-id-char nil)
2771
2772 ;; If you ever change this function, make sure the new version
2773 ;; cannot generate IDs that the old version could.
2774 ;; You might for example insert a "." somewhere (not next to another dot
2775 ;; or string boundary), or modify the "fsf" string.
2776 (defun message-unique-id ()
2777   ;; Don't use microseconds from (current-time), they may be unsupported.
2778   ;; Instead we use this randomly inited counter.
2779   (setq message-unique-id-char
2780         (% (1+ (or message-unique-id-char (logand (random t) (1- (lsh 1 20)))))
2781            ;; (current-time) returns 16-bit ints,
2782            ;; and 2^16*25 just fits into 4 digits i base 36.
2783            (* 25 25)))
2784   (let ((tm (current-time)))
2785     (concat
2786      (if (memq system-type '(ms-dos emx vax-vms))
2787          (let ((user (downcase (user-login-name))))
2788            (while (string-match "[^a-z0-9_]" user)
2789              (aset user (match-beginning 0) ?_))
2790            user)
2791        (message-number-base36 (user-uid) -1))
2792      (message-number-base36 (+ (car   tm)
2793                                (lsh (% message-unique-id-char 25) 16)) 4)
2794      (message-number-base36 (+ (nth 1 tm)
2795                                (lsh (/ message-unique-id-char 25) 16)) 4)
2796      ;; Append the newsreader name, because while the generated
2797      ;; ID is unique to this newsreader, other newsreaders might
2798      ;; otherwise generate the same ID via another algorithm.
2799      ".fsf")))
2800
2801 (defun message-number-base36 (num len)
2802   (if (if (< len 0)
2803           (<= num 0)
2804         (= len 0))
2805       ""
2806     (concat (message-number-base36 (/ num 36) (1- len))
2807             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
2808                                   (% num 36))))))
2809
2810 (defun message-make-organization ()
2811   "Make an Organization header."
2812   (let* ((organization
2813           (when message-user-organization
2814                 (if (message-functionp message-user-organization)
2815                     (funcall message-user-organization)
2816                   message-user-organization))))
2817     (save-excursion
2818       (message-set-work-buffer)
2819       (cond ((stringp organization)
2820              (insert organization))
2821             ((and (eq t organization)
2822                   message-user-organization-file
2823                   (file-exists-p message-user-organization-file))
2824              (insert-file-contents message-user-organization-file)))
2825       (goto-char (point-min))
2826       (while (re-search-forward "[\t\n]+" nil t)
2827         (replace-match "" t t))
2828       (unless (zerop (buffer-size))
2829         (buffer-string)))))
2830
2831 (defun message-make-lines ()
2832   "Count the number of lines and return numeric string."
2833   (save-excursion
2834     (save-restriction
2835       (widen)
2836       (goto-char (point-min))
2837       (re-search-forward
2838        (concat "^" (regexp-quote mail-header-separator) "$"))
2839       (forward-line 1)
2840       (int-to-string (count-lines (point) (point-max))))))
2841
2842 (defun message-make-in-reply-to ()
2843   "Return the In-Reply-To header for this message."
2844   (when message-reply-headers
2845     (let ((from (mail-header-from message-reply-headers))
2846           (date (mail-header-date message-reply-headers)))
2847       (when from
2848         (let ((stop-pos
2849                (string-match "  *at \\|  *@ \\| *(\\| *<" from)))
2850           (concat (if (and stop-pos
2851                            (not (zerop stop-pos)))
2852                       (substring from 0 stop-pos) from)
2853                   "'s message of \""
2854                   (if (or (not date) (string= date ""))
2855                       "(unknown date)" date)
2856                   "\""))))))
2857
2858 (defun message-make-distribution ()
2859   "Make a Distribution header."
2860   (let ((orig-distribution (message-fetch-reply-field "distribution")))
2861     (cond ((message-functionp message-distribution-function)
2862            (funcall message-distribution-function))
2863           (t orig-distribution))))
2864
2865 (defun message-make-expires ()
2866   "Return an Expires header based on `message-expires'."
2867   (let ((current (current-time))
2868         (future (* 1.0 message-expires 60 60 24)))
2869     ;; Add the future to current.
2870     (setcar current (+ (car current) (round (/ future (expt 2 16)))))
2871     (setcar (cdr current) (+ (nth 1 current) (% (round future) (expt 2 16))))
2872     (message-make-date current)))
2873
2874 (defun message-make-path ()
2875   "Return uucp path."
2876   (let ((login-name (user-login-name)))
2877     (cond ((null message-user-path)
2878            (concat (system-name) "!" login-name))
2879           ((stringp message-user-path)
2880            ;; Support GENERICPATH.  Suggested by vixie@decwrl.dec.com.
2881            (concat message-user-path "!" login-name))
2882           (t login-name))))
2883
2884 (defun message-make-from ()
2885   "Make a From header."
2886   (let* ((style message-from-style)
2887          (login (message-make-address))
2888          (fullname
2889           (or (and (boundp 'user-full-name)
2890                    user-full-name)
2891               (user-full-name))))
2892     (when (string= fullname "&")
2893       (setq fullname (user-login-name)))
2894     (save-excursion
2895       (message-set-work-buffer)
2896       (cond
2897        ((or (null style)
2898             (equal fullname ""))
2899         (insert login))
2900        ((or (eq style 'angles)
2901             (and (not (eq style 'parens))
2902                  ;; Use angles if no quoting is needed, or if parens would
2903                  ;; need quoting too.
2904                  (or (not (string-match "[^- !#-'*+/-9=?A-Z^-~]" fullname))
2905                      (let ((tmp (concat fullname nil)))
2906                        (while (string-match "([^()]*)" tmp)
2907                          (aset tmp (match-beginning 0) ?-)
2908                          (aset tmp (1- (match-end 0)) ?-))
2909                        (string-match "[\\()]" tmp)))))
2910         (insert fullname)
2911         (goto-char (point-min))
2912         ;; Look for a character that cannot appear unquoted
2913         ;; according to RFC 822.
2914         (when (re-search-forward "[^- !#-'*+/-9=?A-Z^-~]" nil 1)
2915           ;; Quote fullname, escaping specials.
2916           (goto-char (point-min))
2917           (insert "\"")
2918           (while (re-search-forward "[\"\\]" nil 1)
2919             (replace-match "\\\\\\&" t))
2920           (insert "\""))
2921         (insert " <" login ">"))
2922        (t                               ; 'parens or default
2923         (insert login " (")
2924         (let ((fullname-start (point)))
2925           (insert fullname)
2926           (goto-char fullname-start)
2927           ;; RFC 822 says \ and nonmatching parentheses
2928           ;; must be escaped in comments.
2929           ;; Escape every instance of ()\ ...
2930           (while (re-search-forward "[()\\]" nil 1)
2931             (replace-match "\\\\\\&" t))
2932           ;; ... then undo escaping of matching parentheses,
2933           ;; including matching nested parentheses.
2934           (goto-char fullname-start)
2935           (while (re-search-forward
2936                   "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
2937                   nil 1)
2938             (replace-match "\\1(\\3)" t)
2939             (goto-char fullname-start)))
2940         (insert ")")))
2941       (buffer-string))))
2942
2943 (defun message-make-sender ()
2944   "Return the \"real\" user address.
2945 This function tries to ignore all user modifications, and
2946 give as trustworthy answer as possible."
2947   (concat (user-login-name) "@" (system-name)))
2948
2949 (defun message-make-address ()
2950   "Make the address of the user."
2951   (or (message-user-mail-address)
2952       (concat (user-login-name) "@" (message-make-domain))))
2953
2954 (defun message-user-mail-address ()
2955   "Return the pertinent part of `user-mail-address'."
2956   (when user-mail-address
2957     (if (string-match " " user-mail-address)
2958         (nth 1 (mail-extract-address-components user-mail-address))
2959       user-mail-address)))
2960
2961 (defun message-make-fqdn ()
2962   "Return user's fully qualified domain name."
2963   (let ((system-name (system-name))
2964         (user-mail (message-user-mail-address)))
2965     (cond
2966      ((string-match "[^.]\\.[^.]" system-name)
2967       ;; `system-name' returned the right result.
2968       system-name)
2969      ;; Try `mail-host-address'.
2970      ((and (boundp 'mail-host-address)
2971            (stringp mail-host-address)
2972            (string-match "\\." mail-host-address))
2973       mail-host-address)
2974      ;; We try `user-mail-address' as a backup.
2975      ((and user-mail
2976            (string-match "\\." user-mail)
2977            (string-match "@\\(.*\\)\\'" user-mail))
2978       (match-string 1 user-mail))
2979      ;; Default to this bogus thing.
2980      (t
2981       (concat system-name ".i-did-not-set--mail-host-address--so-shoot-me")))))
2982
2983 (defun message-make-host-name ()
2984   "Return the name of the host."
2985   (let ((fqdn (message-make-fqdn)))
2986     (string-match "^[^.]+\\." fqdn)
2987     (substring fqdn 0 (1- (match-end 0)))))
2988
2989 (defun message-make-domain ()
2990   "Return the domain name."
2991   (or mail-host-address
2992       (message-make-fqdn)))
2993
2994 (defun message-generate-headers (headers)
2995   "Prepare article HEADERS.
2996 Headers already prepared in the buffer are not modified."
2997   (save-restriction
2998     (message-narrow-to-headers)
2999     (let* ((Date (message-make-date))
3000            (Message-ID (message-make-message-id))
3001            (Organization (message-make-organization))
3002            (From (message-make-from))
3003            (Path (message-make-path))
3004            (Subject nil)
3005            (Newsgroups nil)
3006            (In-Reply-To (message-make-in-reply-to))
3007            (To nil)
3008            (Distribution (message-make-distribution))
3009            (Lines (message-make-lines))
3010            (User-Agent message-newsreader)
3011            (Expires (message-make-expires))
3012            (case-fold-search t)
3013            header value elem)
3014       ;; First we remove any old generated headers.
3015       (let ((headers message-deletable-headers))
3016         (unless (buffer-modified-p)
3017           (setq headers (delq 'Message-ID (copy-sequence headers))))
3018         (while headers
3019           (goto-char (point-min))
3020           (and (re-search-forward
3021                 (concat "^" (symbol-name (car headers)) ": *") nil t)
3022                (get-text-property (1+ (match-beginning 0)) 'message-deletable)
3023                (message-delete-line))
3024           (pop headers)))
3025       ;; Go through all the required headers and see if they are in the
3026       ;; articles already.  If they are not, or are empty, they are
3027       ;; inserted automatically - except for Subject, Newsgroups and
3028       ;; Distribution.
3029       (while headers
3030         (goto-char (point-min))
3031         (setq elem (pop headers))
3032         (if (consp elem)
3033             (if (eq (car elem) 'optional)
3034                 (setq header (cdr elem))
3035               (setq header (car elem)))
3036           (setq header elem))
3037         (when (or (not (re-search-forward
3038                         (concat "^"
3039                                 (regexp-quote
3040                                  (downcase
3041                                   (if (stringp header)
3042                                       header
3043                                     (symbol-name header))))
3044                                 ":")
3045                         nil t))
3046                   (progn
3047                     ;; The header was found.  We insert a space after the
3048                     ;; colon, if there is none.
3049                     (if (/= (char-after) ? ) (insert " ") (forward-char 1))
3050                     ;; Find out whether the header is empty...
3051                     (looking-at "[ \t]*\n[^ \t]")))
3052           ;; So we find out what value we should insert.
3053           (setq value
3054                 (cond
3055                  ((and (consp elem) (eq (car elem) 'optional))
3056                   ;; This is an optional header.  If the cdr of this
3057                   ;; is something that is nil, then we do not insert
3058                   ;; this header.
3059                   (setq header (cdr elem))
3060                   (or (and (fboundp (cdr elem)) (funcall (cdr elem)))
3061                       (and (boundp (cdr elem)) (symbol-value (cdr elem)))))
3062                  ((consp elem)
3063                   ;; The element is a cons.  Either the cdr is a
3064                   ;; string to be inserted verbatim, or it is a
3065                   ;; function, and we insert the value returned from
3066                   ;; this function.
3067                   (or (and (stringp (cdr elem)) (cdr elem))
3068                       (and (fboundp (cdr elem)) (funcall (cdr elem)))))
3069                  ((and (boundp header) (symbol-value header))
3070                   ;; The element is a symbol.  We insert the value
3071                   ;; of this symbol, if any.
3072                   (symbol-value header))
3073                  (t
3074                   ;; We couldn't generate a value for this header,
3075                   ;; so we just ask the user.
3076                   (read-from-minibuffer
3077                    (format "Empty header for %s; enter value: " header)))))
3078           ;; Finally insert the header.
3079           (when (and value
3080                      (not (equal value "")))
3081             (save-excursion
3082               (if (bolp)
3083                   (progn
3084                     ;; This header didn't exist, so we insert it.
3085                     (goto-char (point-max))
3086                     (insert (if (stringp header) header (symbol-name header))
3087                             ": " value "\n")
3088                     (forward-line -1))
3089                 ;; The value of this header was empty, so we clear
3090                 ;; totally and insert the new value.
3091                 (delete-region (point) (gnus-point-at-eol))
3092                 (insert value))
3093               ;; Add the deletable property to the headers that require it.
3094               (and (memq header message-deletable-headers)
3095                    (progn (beginning-of-line) (looking-at "[^:]+: "))
3096                    (add-text-properties
3097                     (point) (match-end 0)
3098                     '(message-deletable t face italic) (current-buffer)))))))
3099       ;; Insert new Sender if the From is strange.
3100       (let ((from (message-fetch-field "from"))
3101             (sender (message-fetch-field "sender"))
3102             (secure-sender (message-make-sender)))
3103         (when (and from
3104                    (not (message-check-element 'sender))
3105                    (not (string=
3106                          (downcase
3107                           (cadr (mail-extract-address-components from)))
3108                          (downcase secure-sender)))
3109                    (or (null sender)
3110                        (not
3111                         (string=
3112                          (downcase
3113                           (cadr (mail-extract-address-components sender)))
3114                          (downcase secure-sender)))))
3115           (goto-char (point-min))
3116           ;; Rename any old Sender headers to Original-Sender.
3117           (when (re-search-forward "^\\(Original-\\)*Sender:" nil t)
3118             (beginning-of-line)
3119             (insert "Original-")
3120             (beginning-of-line))
3121           (when (or (message-news-p)
3122                     (string-match "@.+\\.." secure-sender))
3123             (insert "Sender: " secure-sender "\n")))))))
3124
3125 (defun message-insert-courtesy-copy ()
3126   "Insert a courtesy message in mail copies of combined messages."
3127   (let (newsgroups)
3128     (save-excursion
3129       (save-restriction
3130         (message-narrow-to-headers)
3131         (when (setq newsgroups (message-fetch-field "newsgroups"))
3132           (goto-char (point-max))
3133           (insert "Posted-To: " newsgroups "\n")))
3134       (forward-line 1)
3135       (when message-courtesy-message
3136         (cond
3137          ((string-match "%s" message-courtesy-message)
3138           (insert (format message-courtesy-message newsgroups)))
3139          (t
3140           (insert message-courtesy-message)))))))
3141
3142 ;;;
3143 ;;; Setting up a message buffer
3144 ;;;
3145
3146 (defun message-fill-address (header value)
3147   (save-restriction
3148     (narrow-to-region (point) (point))
3149     (insert (capitalize (symbol-name header))
3150             ": "
3151             (if (consp value) (car value) value)
3152             "\n")
3153     (narrow-to-region (point-min) (1- (point-max)))
3154     (let (quoted last)
3155       (goto-char (point-min))
3156       (while (not (eobp))
3157         (skip-chars-forward "^,\"" (point-max))
3158         (if (or (eq (char-after) ?,)
3159                 (eobp))
3160             (when (not quoted)
3161               (if (and (> (current-column) 78)
3162                        last)
3163                   (progn
3164                     (save-excursion
3165                       (goto-char last)
3166                       (insert "\n\t"))
3167                     (setq last (1+ (point))))
3168                 (setq last (1+ (point)))))
3169           (setq quoted (not quoted)))
3170         (unless (eobp)
3171           (forward-char 1))))
3172     (goto-char (point-max))
3173     (widen)
3174     (forward-line 1)))
3175
3176 (defun message-fill-header (header value)
3177   (let ((begin (point))
3178         (fill-column 990)
3179         (fill-prefix "\t"))
3180     (insert (capitalize (symbol-name header))
3181             ": "
3182             (if (consp value) (car value) value)
3183             "\n")
3184     (save-restriction
3185       (narrow-to-region begin (point))
3186       (fill-region-as-paragraph begin (point))
3187       ;; Tapdance around looong Message-IDs.
3188       (forward-line -1)
3189       (when (looking-at "[ \t]*$")
3190         (message-delete-line))
3191       (goto-char begin)
3192       (re-search-forward ":" nil t)
3193       (when (looking-at "\n[ \t]+")
3194         (replace-match " " t t))
3195       (goto-char (point-max)))))
3196
3197 (defun message-shorten-references (header references)
3198   "Limit REFERENCES to be shorter than 988 characters."
3199   (let ((max 988)
3200         (cut 4)
3201         refs)
3202     (with-temp-buffer
3203       (insert references)
3204       (goto-char (point-min))
3205       (while (re-search-forward "<[^>]+>" nil t)
3206         (push (match-string 0) refs))
3207       (setq refs (nreverse refs))
3208       (while (> (length (mapconcat 'identity refs " ")) max)
3209         (when (< (length refs) (1+ cut))
3210           (decf cut))
3211         (setcdr (nthcdr cut refs) (cddr (nthcdr cut refs)))))
3212     (insert (capitalize (symbol-name header)) ": "
3213             (mapconcat 'identity refs " ") "\n")))
3214
3215 (defun message-position-point ()
3216   "Move point to where the user probably wants to find it."
3217   (message-narrow-to-headers)
3218   (cond
3219    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
3220     (search-backward ":" )
3221     (widen)
3222     (forward-char 1)
3223     (if (eq (char-after) ? )
3224         (forward-char 1)
3225       (insert " ")))
3226    (t
3227     (goto-char (point-max))
3228     (widen)
3229     (forward-line 1)
3230     (unless (looking-at "$")
3231       (forward-line 2)))
3232    (sit-for 0)))
3233
3234 (defun message-buffer-name (type &optional to group)
3235   "Return a new (unique) buffer name based on TYPE and TO."
3236   (cond
3237    ;; Generate a new buffer name The Message Way.
3238    ((eq message-generate-new-buffers 'unique)
3239     (generate-new-buffer-name
3240      (concat "*" type
3241              (if to
3242                  (concat " to "
3243                          (or (car (mail-extract-address-components to))
3244                              to) "")
3245                "")
3246              (if (and group (not (string= group ""))) (concat " on " group) "")
3247              "*")))
3248    ;; Check whether `message-generate-new-buffers' is a function,
3249    ;; and if so, call it.
3250    ((message-functionp message-generate-new-buffers)
3251     (funcall message-generate-new-buffers type to group))
3252    ((eq message-generate-new-buffers 'unsent)
3253     (generate-new-buffer-name
3254      (concat "*unsent " type
3255              (if to
3256                  (concat " to "
3257                          (or (car (mail-extract-address-components to))
3258                              to) "")
3259                "")
3260              (if (and group (not (string= group ""))) (concat " on " group) "")
3261              "*")))
3262    ;; Use standard name.
3263    (t
3264     (format "*%s message*" type))))
3265
3266 (defun message-pop-to-buffer (name)
3267   "Pop to buffer NAME, and warn if it already exists and is modified."
3268   (let ((buffer (get-buffer name)))
3269     (if (and buffer
3270              (buffer-name buffer))
3271         (progn
3272           (set-buffer (pop-to-buffer buffer))
3273           (when (and (buffer-modified-p)
3274                      (not (y-or-n-p
3275                            "Message already being composed; erase? ")))
3276             (error "Message being composed")))
3277       (set-buffer (pop-to-buffer name)))
3278     (erase-buffer)
3279     (message-mode)))
3280
3281 (defun message-do-send-housekeeping ()
3282   "Kill old message buffers."
3283   ;; We might have sent this buffer already.  Delete it from the
3284   ;; list of buffers.
3285   (setq message-buffer-list (delq (current-buffer) message-buffer-list))
3286   (while (and message-max-buffers
3287               message-buffer-list
3288               (>= (length message-buffer-list) message-max-buffers))
3289     ;; Kill the oldest buffer -- unless it has been changed.
3290     (let ((buffer (pop message-buffer-list)))
3291       (when (and (buffer-name buffer)
3292                  (not (buffer-modified-p buffer)))
3293         (kill-buffer buffer))))
3294   ;; Rename the buffer.
3295   (if message-send-rename-function
3296       (funcall message-send-rename-function)
3297     (when (string-match "\\`\\*\\(unsent \\)?" (buffer-name))
3298       (rename-buffer
3299        (concat "*sent " (substring (buffer-name) (match-end 0))) t)))
3300   ;; Push the current buffer onto the list.
3301   (when message-max-buffers
3302     (setq message-buffer-list
3303           (nconc message-buffer-list (list (current-buffer))))))
3304
3305 (defvar mc-modes-alist)
3306 (defun message-setup (headers &optional replybuffer actions)
3307   (when (and (boundp 'mc-modes-alist)
3308              (not (assq 'message-mode mc-modes-alist)))
3309     (push '(message-mode (encrypt . mc-encrypt-message)
3310                          (sign . mc-sign-message))
3311           mc-modes-alist))
3312   (when actions
3313     (setq message-send-actions actions))
3314   (setq message-reply-buffer replybuffer)
3315   (goto-char (point-min))
3316   ;; Insert all the headers.
3317   (mail-header-format
3318    (let ((h headers)
3319          (alist message-header-format-alist))
3320      (while h
3321        (unless (assq (caar h) message-header-format-alist)
3322          (push (list (caar h)) alist))
3323        (pop h))
3324      alist)
3325    headers)
3326   (delete-region (point) (progn (forward-line -1) (point)))
3327   (when message-default-headers
3328     (insert message-default-headers)
3329     (or (bolp) (insert ?\n)))
3330   (put-text-property
3331    (point)
3332    (progn
3333      (insert mail-header-separator "\n")
3334      (1- (point)))
3335    'read-only nil)
3336   (forward-line -1)
3337   (when (message-news-p)
3338     (when message-default-news-headers
3339       (insert message-default-news-headers)
3340       (or (bolp) (insert ?\n)))
3341     (when message-generate-headers-first
3342       (message-generate-headers
3343        (delq 'Lines
3344              (delq 'Subject
3345                    (copy-sequence message-required-news-headers))))))
3346   (when (message-mail-p)
3347     (when message-default-mail-headers
3348       (insert message-default-mail-headers)
3349       (or (bolp) (insert ?\n)))
3350     (when message-generate-headers-first
3351       (message-generate-headers
3352        (delq 'Lines
3353              (delq 'Subject
3354                    (copy-sequence message-required-mail-headers))))))
3355   (run-hooks 'message-signature-setup-hook)
3356   (message-insert-signature)
3357   (save-restriction
3358     (message-narrow-to-headers)
3359     (run-hooks 'message-header-setup-hook))
3360   (set-buffer-modified-p nil)
3361   (setq buffer-undo-list nil)
3362   (run-hooks 'message-setup-hook)
3363   (message-position-point)
3364   (undo-boundary))
3365
3366 (defun message-set-auto-save-file-name ()
3367   "Associate the message buffer with a file in the drafts directory."
3368   (when message-auto-save-directory
3369     (if (gnus-alive-p)
3370         (setq message-draft-article
3371               (nndraft-request-associate-buffer "drafts"))
3372       (setq buffer-file-name (expand-file-name "*message*"
3373                                                message-auto-save-directory))
3374       (setq buffer-auto-save-file-name (make-auto-save-file-name)))
3375     (clear-visited-file-modtime)
3376     (setq buffer-file-coding-system message-draft-coding-system)))
3377
3378 (defun message-disassociate-draft ()
3379   "Disassociate the message buffer from the drafts directory."
3380   (when message-draft-article
3381     (nndraft-request-expire-articles
3382      (list message-draft-article) "drafts" nil t)))
3383
3384 (defun message-insert-headers ()
3385   "Generate the headers for the article."
3386   (interactive)
3387   (save-excursion
3388     (save-restriction
3389       (message-narrow-to-headers)
3390       (when (message-news-p)
3391         (message-generate-headers
3392          (delq 'Lines
3393                (delq 'Subject
3394                      (copy-sequence message-required-news-headers)))))
3395       (when (message-mail-p)
3396         (message-generate-headers
3397          (delq 'Lines
3398                (delq 'Subject
3399                      (copy-sequence message-required-mail-headers))))))))
3400
3401 \f
3402
3403 ;;;
3404 ;;; Commands for interfacing with message
3405 ;;;
3406
3407 ;;;###autoload
3408 (defun message-mail (&optional to subject
3409                                other-headers continue switch-function
3410                                yank-action send-actions)
3411   "Start editing a mail message to be sent.
3412 OTHER-HEADERS is an alist of header/value pairs."
3413   (interactive)
3414   (let ((message-this-is-mail t))
3415     (message-pop-to-buffer (message-buffer-name "mail" to))
3416     (message-setup
3417      (nconc
3418       `((To . ,(or to "")) (Subject . ,(or subject "")))
3419       (when other-headers other-headers)))))
3420
3421 ;;;###autoload
3422 (defun message-news (&optional newsgroups subject)
3423   "Start editing a news article to be sent."
3424   (interactive)
3425   (let ((message-this-is-news t))
3426     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups))
3427     (message-setup `((Newsgroups . ,(or newsgroups ""))
3428                      (Subject . ,(or subject ""))))))
3429
3430 ;;;###autoload
3431 (defun message-reply (&optional to-address wide)
3432   "Start editing a reply to the article in the current buffer."
3433   (interactive)
3434   (let ((cur (current-buffer))
3435         from subject date reply-to to cc
3436         references message-id follow-to
3437         (inhibit-point-motion-hooks t)
3438         (message-this-is-mail t)
3439         mct never-mct gnus-warning)
3440     (save-restriction
3441       (message-narrow-to-head)
3442       ;; Allow customizations to have their say.
3443       (if (not wide)
3444           ;; This is a regular reply.
3445           (if (message-functionp message-reply-to-function)
3446               (setq follow-to (funcall message-reply-to-function)))
3447         ;; This is a followup.
3448         (if (message-functionp message-wide-reply-to-function)
3449             (save-excursion
3450               (setq follow-to
3451                     (funcall message-wide-reply-to-function)))))
3452       ;; Find all relevant headers we need.
3453       (setq from (message-fetch-field "from")
3454             date (message-fetch-field "date")
3455             subject (or (message-fetch-field "subject") "none")
3456             to (message-fetch-field "to")
3457             cc (message-fetch-field "cc")
3458             mct (message-fetch-field "mail-copies-to")
3459             reply-to (message-fetch-field "reply-to")
3460             references (message-fetch-field "references")
3461             message-id (message-fetch-field "message-id" t))
3462       ;; Remove any (buggy) Re:'s that are present and make a
3463       ;; proper one.
3464       (when (string-match message-subject-re-regexp subject)
3465         (setq subject (substring subject (match-end 0))))
3466       (setq subject (concat "Re: " subject))
3467
3468       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
3469                  (string-match "<[^>]+>" gnus-warning))
3470         (setq message-id (match-string 0 gnus-warning)))
3471
3472       ;; Handle special values of Mail-Copies-To.
3473       (when mct
3474         (cond ((or (equal (downcase mct) "never")
3475                    (equal (downcase mct) "nobody"))
3476                (setq never-mct t)
3477                (setq mct nil))
3478               ((or (equal (downcase mct) "always")
3479                    (equal (downcase mct) "poster"))
3480                (setq mct (or reply-to from)))))
3481
3482       (unless follow-to
3483         (if (or (not wide)
3484                 to-address)
3485             (progn
3486               (setq follow-to (list (cons 'To (or to-address reply-to from))))
3487               (when (and wide mct)
3488                 (push (cons 'Cc mct) follow-to)))
3489           (let (ccalist)
3490             (save-excursion
3491               (message-set-work-buffer)
3492               (unless never-mct
3493                 (insert (or reply-to from "")))
3494               (insert (if to (concat (if (bolp) "" ", ") to "") ""))
3495               (insert (if mct (concat (if (bolp) "" ", ") mct) ""))
3496               (insert (if cc (concat (if (bolp) "" ", ") cc) ""))
3497               (goto-char (point-min))
3498               (while (re-search-forward "[ \t]+" nil t)
3499                 (replace-match " " t t))
3500               ;; Remove addresses that match `rmail-dont-reply-to-names'.
3501               (let ((rmail-dont-reply-to-names message-dont-reply-to-names))
3502                 (insert (prog1 (rmail-dont-reply-to (buffer-string))
3503                           (erase-buffer))))
3504               (goto-char (point-min))
3505               ;; Perhaps Mail-Copies-To: never removed the only address?
3506               (when (eobp)
3507                 (insert (or reply-to from "")))
3508               (setq ccalist
3509                     (mapcar
3510                      (lambda (addr)
3511                        (cons (mail-strip-quoted-names addr) addr))
3512                      (message-tokenize-header (buffer-string))))
3513               (let ((s ccalist))
3514                 (while s
3515                   (setq ccalist (delq (assoc (car (pop s)) s) ccalist)))))
3516             (setq follow-to (list (cons 'To (cdr (pop ccalist)))))
3517             (when ccalist
3518               (let ((ccs (cons 'Cc (mapconcat
3519                                     (lambda (addr) (cdr addr)) ccalist ", "))))
3520                 (when (string-match "^ +" (cdr ccs))
3521                   (setcdr ccs (substring (cdr ccs) (match-end 0))))
3522                 (push ccs follow-to))))))
3523       (widen))
3524
3525     (message-pop-to-buffer (message-buffer-name
3526                             (if wide "wide reply" "reply") from
3527                             (if wide to-address nil)))
3528
3529     (setq message-reply-headers
3530           (vector 0 subject from date message-id references 0 0 ""))
3531
3532     (message-setup
3533      `((Subject . ,subject)
3534        ,@follow-to
3535        ,@(if (or references message-id)
3536              `((References . ,(concat (or references "") (and references " ")
3537                                       (or message-id ""))))
3538            nil))
3539      cur)))
3540
3541 ;;;###autoload
3542 (defun message-wide-reply (&optional to-address)
3543   "Make a \"wide\" reply to the message in the current buffer."
3544   (interactive)
3545   (message-reply to-address t))
3546
3547 ;;;###autoload
3548 (defun message-followup (&optional to-newsgroups)
3549   "Follow up to the message in the current buffer.
3550 If TO-NEWSGROUPS, use that as the new Newsgroups line."
3551   (interactive)
3552   (let ((cur (current-buffer))
3553         from subject date reply-to mct
3554         references message-id follow-to
3555         (inhibit-point-motion-hooks t)
3556         (message-this-is-news t)
3557         followup-to distribution newsgroups gnus-warning posted-to)
3558     (save-restriction
3559       (narrow-to-region
3560        (goto-char (point-min))
3561        (if (search-forward "\n\n" nil t)
3562            (1- (point))
3563          (point-max)))
3564       (when (message-functionp message-followup-to-function)
3565         (setq follow-to
3566               (funcall message-followup-to-function)))
3567       (setq from (message-fetch-field "from")
3568             date (message-fetch-field "date")
3569             subject (or (message-fetch-field "subject") "none")
3570             references (message-fetch-field "references")
3571             message-id (message-fetch-field "message-id" t)
3572             followup-to (message-fetch-field "followup-to")
3573             newsgroups (message-fetch-field "newsgroups")
3574             posted-to (message-fetch-field "posted-to")
3575             reply-to (message-fetch-field "reply-to")
3576             distribution (message-fetch-field "distribution")
3577             mct (message-fetch-field "mail-copies-to"))
3578       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
3579                  (string-match "<[^>]+>" gnus-warning))
3580         (setq message-id (match-string 0 gnus-warning)))
3581       ;; Remove bogus distribution.
3582       (when (and (stringp distribution)
3583                  (let ((case-fold-search t))
3584                    (string-match "world" distribution)))
3585         (setq distribution nil))
3586       ;; Remove any (buggy) Re:'s that are present and make a
3587       ;; proper one.
3588       (when (string-match message-subject-re-regexp subject)
3589         (setq subject (substring subject (match-end 0))))
3590       (setq subject (concat "Re: " subject))
3591       (widen))
3592
3593     (message-pop-to-buffer (message-buffer-name "followup" from newsgroups))
3594
3595     (message-setup
3596      `((Subject . ,subject)
3597        ,@(cond
3598           (to-newsgroups
3599            (list (cons 'Newsgroups to-newsgroups)))
3600           (follow-to follow-to)
3601           ((and followup-to message-use-followup-to)
3602            (list
3603             (cond
3604              ((equal (downcase followup-to) "poster")
3605               (if (or (eq message-use-followup-to 'use)
3606                       (message-y-or-n-p "Obey Followup-To: poster? " t "\
3607 You should normally obey the Followup-To: header.
3608
3609 `Followup-To: poster' sends your response via e-mail instead of news.
3610
3611 A typical situation where `Followup-To: poster' is used is when the poster
3612 does not read the newsgroup, so he wouldn't see any replies sent to it."))
3613                   (progn
3614                     (setq message-this-is-news nil)
3615                     (cons 'To (or reply-to from "")))
3616                 (cons 'Newsgroups newsgroups)))
3617              (t
3618               (if (or (equal followup-to newsgroups)
3619                       (not (eq message-use-followup-to 'ask))
3620                       (message-y-or-n-p
3621                        (concat "Obey Followup-To: " followup-to "? ") t "\
3622 You should normally obey the Followup-To: header.
3623
3624         `Followup-To: " followup-to "'
3625 directs your response to " (if (string-match "," followup-to)
3626                                "the specified newsgroups"
3627                              "that newsgroup only") ".
3628
3629 If a message is posted to several newsgroups, Followup-To is often
3630 used to direct the following discussion to one newsgroup only,
3631 because discussions that are spread over several newsgroup tend to
3632 be fragmented and very difficult to follow.
3633
3634 Also, some source/announcement newsgroups are not indented for discussion;
3635 responses here are directed to other newsgroups."))
3636                   (cons 'Newsgroups followup-to)
3637                 (cons 'Newsgroups newsgroups))))))
3638           (posted-to
3639            `((Newsgroups . ,posted-to)))
3640           (t
3641            `((Newsgroups . ,newsgroups))))
3642        ,@(and distribution (list (cons 'Distribution distribution)))
3643        ,@(if (or references message-id)
3644              `((References . ,(concat (or references "") (and references " ")
3645                                       (or message-id "")))))
3646        ,@(when (and mct
3647                     (not (or (equal (downcase mct) "never")
3648                              (equal (downcase mct) "nobody"))))
3649            (list (cons 'Cc (if (or (equal (downcase mct) "always")
3650                                    (equal (downcase mct) "poster"))
3651                                (or reply-to from "")
3652                              mct)))))
3653
3654      cur)
3655
3656     (setq message-reply-headers
3657           (vector 0 subject from date message-id references 0 0 ""))))
3658
3659
3660 ;;;###autoload
3661 (defun message-cancel-news ()
3662   "Cancel an article you posted."
3663   (interactive)
3664   (unless (message-news-p)
3665     (error "This is not a news article; canceling is impossible"))
3666   (when (yes-or-no-p "Do you really want to cancel this article? ")
3667     (let (from newsgroups message-id distribution buf sender)
3668       (save-excursion
3669         ;; Get header info. from original article.
3670         (save-restriction
3671           (message-narrow-to-head)
3672           (setq from (message-fetch-field "from")
3673                 sender (message-fetch-field "sender")
3674                 newsgroups (message-fetch-field "newsgroups")
3675                 message-id (message-fetch-field "message-id" t)
3676                 distribution (message-fetch-field "distribution")))
3677         ;; Make sure that this article was written by the user.
3678         (unless (or (and sender
3679                          (string-equal
3680                           (downcase sender)
3681                           (downcase (message-make-sender))))
3682                     (string-equal
3683                      (downcase (cadr (mail-extract-address-components from)))
3684                      (downcase (cadr (mail-extract-address-components
3685                                       (message-make-from))))))
3686           (error "This article is not yours"))
3687         ;; Make control message.
3688         (setq buf (set-buffer (get-buffer-create " *message cancel*")))
3689         (erase-buffer)
3690         (insert "Newsgroups: " newsgroups "\n"
3691                 "From: " (message-make-from) "\n"
3692                 "Subject: cmsg cancel " message-id "\n"
3693                 "Control: cancel " message-id "\n"
3694                 (if distribution
3695                     (concat "Distribution: " distribution "\n")
3696                   "")
3697                 mail-header-separator "\n"
3698                 message-cancel-message)
3699         (run-hooks 'message-cancel-hook)
3700         (message "Canceling your article...")
3701         (if (let ((message-syntax-checks
3702                    'dont-check-for-anything-just-trust-me))
3703               (funcall message-send-news-function))
3704             (message "Canceling your article...done"))
3705         (kill-buffer buf)))))
3706
3707 ;;;###autoload
3708 (defun message-supersede ()
3709   "Start composing a message to supersede the current message.
3710 This is done simply by taking the old article and adding a Supersedes
3711 header line with the old Message-ID."
3712   (interactive)
3713   (let ((cur (current-buffer))
3714         (sender (message-fetch-field "sender"))
3715         (from (message-fetch-field "from")))
3716     ;; Check whether the user owns the article that is to be superseded.
3717     (unless (or (and sender
3718                      (string-equal
3719                       (downcase sender)
3720                       (downcase (message-make-sender))))
3721                 (string-equal
3722                  (downcase (cadr (mail-extract-address-components from)))
3723                  (downcase (cadr (mail-extract-address-components
3724                                   (message-make-from))))))
3725       (error "This article is not yours"))
3726     ;; Get a normal message buffer.
3727     (message-pop-to-buffer (message-buffer-name "supersede"))
3728     (insert-buffer-substring cur)
3729     (message-narrow-to-head)
3730     ;; Remove unwanted headers.
3731     (when message-ignored-supersedes-headers
3732       (message-remove-header message-ignored-supersedes-headers t))
3733     (goto-char (point-min))
3734     (if (not (re-search-forward "^Message-ID: " nil t))
3735         (error "No Message-ID in this article")
3736       (replace-match "Supersedes: " t t))
3737     (goto-char (point-max))
3738     (insert mail-header-separator)
3739     (widen)
3740     (forward-line 1)))
3741
3742 ;;;###autoload
3743 (defun message-recover ()
3744   "Reread contents of current buffer from its last auto-save file."
3745   (interactive)
3746   (let ((file-name (make-auto-save-file-name)))
3747     (cond ((save-window-excursion
3748              (if (not (eq system-type 'vax-vms))
3749                  (with-output-to-temp-buffer "*Directory*"
3750                    (buffer-disable-undo standard-output)
3751                    (let ((default-directory "/"))
3752                      (call-process
3753                       "ls" nil standard-output nil "-l" file-name))))
3754              (yes-or-no-p (format "Recover auto save file %s? " file-name)))
3755            (let ((buffer-read-only nil))
3756              (erase-buffer)
3757              (insert-file-contents file-name nil)))
3758           (t (error "message-recover cancelled")))))
3759
3760 ;;; Washing Subject:
3761
3762 (defun message-wash-subject (subject)
3763   "Remove junk like \"Re:\", \"(fwd)\", etc. that was added to the subject by previous forwarders, replyers, etc."
3764   (with-temp-buffer
3765     (insert-string subject)
3766     (goto-char (point-min))
3767     ;; strip Re/Fwd stuff off the beginning
3768     (while (re-search-forward
3769             "\\([Rr][Ee]:\\|[Ff][Ww][Dd]\\(\\[[0-9]*\\]\\)?:\\|[Ff][Ww]:\\)" nil t)
3770       (replace-match ""))
3771
3772     ;; and gnus-style forwards [foo@bar.com] subject
3773     (goto-char (point-min))
3774     (while (re-search-forward "\\[[^ \t]*\\(@\\|\\.\\)[^ \t]*\\]" nil t)
3775       (replace-match ""))
3776
3777     ;; and off the end
3778     (goto-char (point-max))
3779     (while (re-search-backward "([Ff][Ww][Dd])" nil t)
3780       (replace-match ""))
3781
3782     ;; and finally, any whitespace that was left-over
3783     (goto-char (point-min))
3784     (while (re-search-forward "^[ \t]+" nil t)
3785       (replace-match ""))
3786     (goto-char (point-max))
3787     (while (re-search-backward "[ \t]+$" nil t)
3788       (replace-match ""))
3789
3790     (buffer-string)))
3791
3792 ;;; Forwarding messages.
3793
3794 (defun message-forward-subject-author-subject (subject)
3795   "Generate a subject for a forwarded message.
3796 The form is: [Source] Subject, where if the original message was mail,
3797 Source is the sender, and if the original message was news, Source is
3798 the list of newsgroups is was posted to."
3799   (concat "["
3800           (or (message-fetch-field
3801                (if (message-news-p) "newsgroups" "from"))
3802               "(nowhere)")
3803           "] " subject))
3804
3805 (defun message-forward-subject-fwd (subject)
3806   "Generate a subject for a forwarded message.
3807 The form is: Fwd: Subject, where Subject is the original subject of
3808 the message."
3809   (concat "Fwd: " subject))
3810
3811 (defun message-make-forward-subject ()
3812   "Return a Subject header suitable for the message in the current buffer."
3813   (save-excursion
3814     (save-restriction
3815       (current-buffer)
3816       (message-narrow-to-head)
3817       (let ((funcs message-make-forward-subject-function)
3818             (subject (if message-wash-forwarded-subjects
3819                          (message-wash-subject
3820                           (or (message-fetch-field "Subject") ""))
3821                        (or (message-fetch-field "Subject") ""))))
3822         ;; Make sure funcs is a list.
3823         (and funcs
3824              (not (listp funcs))
3825              (setq funcs (list funcs)))
3826         ;; Apply funcs in order, passing subject generated by previous
3827         ;; func to the next one.
3828         (while funcs
3829           (when (message-functionp (car funcs))
3830             (setq subject (funcall (car funcs) subject)))
3831           (setq funcs (cdr funcs)))
3832         subject))))
3833
3834 ;;;###autoload
3835 (defun message-forward (&optional news)
3836   "Forward the current message via mail.
3837 Optional NEWS will use news to forward instead of mail."
3838   (interactive "P")
3839   (let ((cur (current-buffer))
3840         (subject (message-make-forward-subject))
3841         art-beg)
3842     (if news
3843         (message-news nil subject)
3844       (message-mail nil subject))
3845     ;; Put point where we want it before inserting the forwarded
3846     ;; message.
3847     (message-goto-body)
3848     (if message-forward-as-mime
3849          (insert "\n\n<#part type=message/rfc822 disposition=inline>\n")
3850       (insert "\n\n"))
3851     (let ((b (point))
3852           e)
3853       (mml-insert-buffer cur)
3854       (setq e (point))
3855       (and message-forward-as-mime
3856            (insert "<#/part>\n"))
3857       (when (and (not current-prefix-arg)
3858                  message-forward-ignored-headers)
3859         (save-restriction
3860           (narrow-to-region b e)
3861           (goto-char b)
3862           (narrow-to-region (point) (or (search-forward "\n\n" nil t) (point)))
3863           (message-remove-header message-forward-ignored-headers t))))
3864     (message-position-point)))
3865
3866 ;;;###autoload
3867 (defun message-resend (address)
3868   "Resend the current article to ADDRESS."
3869   (interactive
3870    (list (message-read-from-minibuffer "Resend message to: ")))
3871   (message "Resending message to %s..." address)
3872   (save-excursion
3873     (let ((cur (current-buffer))
3874           beg)
3875       ;; We first set up a normal mail buffer.
3876       (set-buffer (get-buffer-create " *message resend*"))
3877       (erase-buffer)
3878       (message-setup `((To . ,address)))
3879       ;; Insert our usual headers.
3880       (message-generate-headers '(From Date To))
3881       (message-narrow-to-headers)
3882       ;; Rename them all to "Resent-*".
3883       (while (re-search-forward "^[A-Za-z]" nil t)
3884         (forward-char -1)
3885         (insert "Resent-"))
3886       (widen)
3887       (forward-line)
3888       (delete-region (point) (point-max))
3889       (setq beg (point))
3890       ;; Insert the message to be resent.
3891       (insert-buffer-substring cur)
3892       (goto-char (point-min))
3893       (search-forward "\n\n")
3894       (forward-char -1)
3895       (save-restriction
3896         (narrow-to-region beg (point))
3897         (message-remove-header message-ignored-resent-headers t)
3898         (goto-char (point-max)))
3899       (insert mail-header-separator)
3900       ;; Rename all old ("Also-")Resent headers.
3901       (while (re-search-backward "^\\(Also-\\)*Resent-" beg t)
3902         (beginning-of-line)
3903         (insert "Also-"))
3904       ;; Quote any "From " lines at the beginning.
3905       (goto-char beg)
3906       (when (looking-at "From ")
3907         (replace-match "X-From-Line: "))
3908       ;; Send it.
3909       (let ((message-inhibit-body-encoding t)
3910             message-required-mail-headers)
3911         (message-send-mail))
3912       (kill-buffer (current-buffer)))
3913     (message "Resending message to %s...done" address)))
3914
3915 ;;;###autoload
3916 (defun message-bounce ()
3917   "Re-mail the current message.
3918 This only makes sense if the current message is a bounce message than
3919 contains some mail you have written which has been bounced back to
3920 you."
3921   (interactive)
3922   (let ((handles (mm-dissect-buffer t))
3923         boundary)
3924     (message-pop-to-buffer (message-buffer-name "bounce"))
3925     (if (stringp (car handles))
3926         ;; This is a MIME bounce.
3927         (mm-insert-part (car (last handles)))
3928       ;; This is a non-MIME bounce, so we try to remove things
3929       ;; manually.
3930       (mm-insert-part handles)
3931       (undo-boundary)
3932       (goto-char (point-min))
3933       (search-forward "\n\n" nil t)
3934       (or (and (re-search-forward message-unsent-separator nil t)
3935                (forward-line 1))
3936           (re-search-forward "^Return-Path:.*\n" nil t))
3937       ;; We remove everything before the bounced mail.
3938       (delete-region
3939        (point-min)
3940        (if (re-search-forward "^[^ \n\t]+:" nil t)
3941            (match-beginning 0)
3942          (point))))
3943     (save-restriction
3944       (message-narrow-to-head)
3945       (message-remove-header message-ignored-bounced-headers t)
3946       (goto-char (point-max))
3947       (insert mail-header-separator))
3948     (message-position-point)))
3949
3950 ;;;
3951 ;;; Interactive entry points for new message buffers.
3952 ;;;
3953
3954 ;;;###autoload
3955 (defun message-mail-other-window (&optional to subject)
3956   "Like `message-mail' command, but display mail buffer in another window."
3957   (interactive)
3958   (let ((pop-up-windows t)
3959         (special-display-buffer-names nil)
3960         (special-display-regexps nil)
3961         (same-window-buffer-names nil)
3962         (same-window-regexps nil))
3963     (message-pop-to-buffer (message-buffer-name "mail" to)))
3964   (let ((message-this-is-mail t))
3965     (message-setup `((To . ,(or to "")) (Subject . ,(or subject ""))))))
3966
3967 ;;;###autoload
3968 (defun message-mail-other-frame (&optional to subject)
3969   "Like `message-mail' command, but display mail buffer in another frame."
3970   (interactive)
3971   (let ((pop-up-frames t)
3972         (special-display-buffer-names nil)
3973         (special-display-regexps nil)
3974         (same-window-buffer-names nil)
3975         (same-window-regexps nil))
3976     (message-pop-to-buffer (message-buffer-name "mail" to)))
3977   (let ((message-this-is-mail t))
3978     (message-setup `((To . ,(or to "")) (Subject . ,(or subject ""))))))
3979
3980 ;;;###autoload
3981 (defun message-news-other-window (&optional newsgroups subject)
3982   "Start editing a news article to be sent."
3983   (interactive)
3984   (let ((pop-up-windows t)
3985         (special-display-buffer-names nil)
3986         (special-display-regexps nil)
3987         (same-window-buffer-names nil)
3988         (same-window-regexps nil))
3989     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
3990   (let ((message-this-is-news t))
3991     (message-setup `((Newsgroups . ,(or newsgroups ""))
3992                      (Subject . ,(or subject ""))))))
3993
3994 ;;;###autoload
3995 (defun message-news-other-frame (&optional newsgroups subject)
3996   "Start editing a news article to be sent."
3997   (interactive)
3998   (let ((pop-up-frames t)
3999         (special-display-buffer-names nil)
4000         (special-display-regexps nil)
4001         (same-window-buffer-names nil)
4002         (same-window-regexps nil))
4003     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
4004   (let ((message-this-is-news t))
4005     (message-setup `((Newsgroups . ,(or newsgroups ""))
4006                      (Subject . ,(or subject ""))))))
4007
4008 ;;; underline.el
4009
4010 ;; This code should be moved to underline.el (from which it is stolen).
4011
4012 ;;;###autoload
4013 (defun bold-region (start end)
4014   "Bold all nonblank characters in the region.
4015 Works by overstriking characters.
4016 Called from program, takes two arguments START and END
4017 which specify the range to operate on."
4018   (interactive "r")
4019   (save-excursion
4020     (let ((end1 (make-marker)))
4021       (move-marker end1 (max start end))
4022       (goto-char (min start end))
4023       (while (< (point) end1)
4024         (or (looking-at "[_\^@- ]")
4025             (insert (char-after) "\b"))
4026         (forward-char 1)))))
4027
4028 ;;;###autoload
4029 (defun unbold-region (start end)
4030   "Remove all boldness (overstruck characters) in the region.
4031 Called from program, takes two arguments START and END
4032 which specify the range to operate on."
4033   (interactive "r")
4034   (save-excursion
4035     (let ((end1 (make-marker)))
4036       (move-marker end1 (max start end))
4037       (goto-char (min start end))
4038       (while (re-search-forward "\b" end1 t)
4039         (if (eq (char-after) (char-after (- (point) 2)))
4040             (delete-char -2))))))
4041
4042 (defalias 'message-exchange-point-and-mark 'exchange-point-and-mark)
4043
4044 ;; Support for toolbar
4045 (when (string-match "XEmacs\\|Lucid" emacs-version)
4046   (require 'messagexmas))
4047
4048 ;;; Group name completion.
4049
4050 (defvar message-newgroups-header-regexp
4051   "^\\(Newsgroups\\|Followup-To\\|Posted-To\\|Gcc\\):"
4052   "Regexp that match headers that lists groups.")
4053
4054 (defun message-tab ()
4055   "Expand group names in Newsgroups and Followup-To headers.
4056 Do a `tab-to-tab-stop' if not in those headers."
4057   (interactive)
4058   (if (let ((mail-abbrev-mode-regexp message-newgroups-header-regexp))
4059         (mail-abbrev-in-expansion-header-p))
4060       (message-expand-group)
4061     (tab-to-tab-stop)))
4062
4063 (defvar gnus-active-hashtb)
4064 (defun message-expand-group ()
4065   "Expand the group name under point."
4066   (let* ((b (save-excursion
4067               (save-restriction
4068                 (narrow-to-region
4069                  (save-excursion
4070                    (beginning-of-line)
4071                    (skip-chars-forward "^:")
4072                    (1+ (point)))
4073                  (point))
4074                 (skip-chars-backward "^, \t\n") (point))))
4075          (completion-ignore-case t)
4076          (string (buffer-substring b (progn (skip-chars-forward "^,\t\n ")
4077                                             (point))))
4078          (hashtb (and (boundp 'gnus-active-hashtb) gnus-active-hashtb))
4079          (completions (all-completions string hashtb))
4080          comp)
4081     (delete-region b (point))
4082     (cond
4083      ((= (length completions) 1)
4084       (if (string= (car completions) string)
4085           (progn
4086             (insert string)
4087             (message "Only matching group"))
4088         (insert (car completions))))
4089      ((and (setq comp (try-completion string hashtb))
4090            (not (string= comp string)))
4091       (insert comp))
4092      (t
4093       (insert string)
4094       (if (not comp)
4095           (message "No matching groups")
4096         (save-selected-window
4097           (pop-to-buffer "*Completions*")
4098           (buffer-disable-undo)
4099           (let ((buffer-read-only nil))
4100             (erase-buffer)
4101             (let ((standard-output (current-buffer)))
4102               (display-completion-list (sort completions 'string<)))
4103             (goto-char (point-min))
4104             (delete-region (point) (progn (forward-line 3) (point))))))))))
4105
4106 ;;; Help stuff.
4107
4108 (defun message-talkative-question (ask question show &rest text)
4109   "Call FUNCTION with argument QUESTION; optionally display TEXT... args.
4110 If SHOW is non-nil, the arguments TEXT... are displayed in a temp buffer.
4111 The following arguments may contain lists of values."
4112   (if (and show
4113            (setq text (message-flatten-list text)))
4114       (save-window-excursion
4115         (save-excursion
4116           (with-output-to-temp-buffer " *MESSAGE information message*"
4117             (set-buffer " *MESSAGE information message*")
4118             (mapcar 'princ text)
4119             (goto-char (point-min))))
4120         (funcall ask question))
4121     (funcall ask question)))
4122
4123 (defun message-flatten-list (list)
4124   "Return a new, flat list that contains all elements of LIST.
4125
4126 \(message-flatten-list '(1 (2 3 (4 5 (6))) 7))
4127 => (1 2 3 4 5 6 7)"
4128   (cond ((consp list)
4129          (apply 'append (mapcar 'message-flatten-list list)))
4130         (list
4131          (list list))))
4132
4133 (defun message-generate-new-buffer-clone-locals (name &optional varstr)
4134   "Create and return a buffer with a name based on NAME using generate-new-buffer.
4135 Then clone the local variables and values from the old buffer to the
4136 new one, cloning only the locals having a substring matching the
4137 regexp varstr."
4138   (let ((oldbuf (current-buffer)))
4139     (save-excursion
4140       (set-buffer (generate-new-buffer name))
4141       (message-clone-locals oldbuf)
4142       (current-buffer))))
4143
4144 (defun message-clone-locals (buffer)
4145   "Clone the local variables from BUFFER to the current buffer."
4146   (let ((locals (save-excursion
4147                   (set-buffer buffer)
4148                   (buffer-local-variables)))
4149         (regexp "^gnus\\|^nn\\|^message"))
4150     (mapcar
4151      (lambda (local)
4152        (when (and (consp local)
4153                   (car local)
4154                   (string-match regexp (symbol-name (car local))))
4155          (ignore-errors
4156            (set (make-local-variable (car local))
4157                 (cdr local)))))
4158      locals)))
4159
4160 ;;; Miscellaneous functions
4161
4162 ;; stolen (and renamed) from nnheader.el
4163 (defun message-replace-chars-in-string (string from to)
4164   "Replace characters in STRING from FROM to TO."
4165   (let ((string (substring string 0))   ;Copy string.
4166         (len (length string))
4167         (idx 0))
4168     ;; Replace all occurrences of FROM with TO.
4169     (while (< idx len)
4170       (when (= (aref string idx) from)
4171         (aset string idx to))
4172       (setq idx (1+ idx)))
4173     string))
4174
4175 ;;;
4176 ;;; MIME functions
4177 ;;;
4178
4179 (defvar message-inhibit-body-encoding nil)
4180
4181 (defun message-encode-message-body ()
4182   (unless message-inhibit-body-encoding 
4183     (let ((mail-parse-charset (or mail-parse-charset
4184                                   message-default-charset
4185                                   message-posting-charset))
4186           (case-fold-search t)
4187           lines content-type-p)
4188       (message-goto-body)
4189       (save-restriction
4190         (narrow-to-region (point) (point-max))
4191         (let ((new (mml-generate-mime)))
4192           (when new
4193             (delete-region (point-min) (point-max))
4194             (insert new)
4195             (goto-char (point-min))
4196             (if (eq (aref new 0) ?\n)
4197                 (delete-char 1)
4198               (search-forward "\n\n")
4199               (setq lines (buffer-substring (point-min) (1- (point))))
4200               (delete-region (point-min)  (point))))))
4201       (save-restriction
4202         (message-narrow-to-headers-or-head)
4203         (message-remove-header "Mime-Version")
4204         (goto-char (point-max))
4205         (insert "MIME-Version: 1.0\n")
4206         (when lines
4207           (insert lines))
4208         (setq content-type-p
4209               (re-search-backward "^Content-Type:" nil t)))
4210       (save-restriction
4211         (message-narrow-to-headers-or-head)
4212         (message-remove-first-header "Content-Type")
4213         (message-remove-first-header "Content-Transfer-Encoding"))
4214       ;; We always make sure that the message has a Content-Type header.
4215       ;; This is because some broken MTAs and MUAs get awfully confused
4216       ;; when confronted with a message with a MIME-Version header and
4217       ;; without a Content-Type header.  For instance, Solaris'
4218       ;; /usr/bin/mail.
4219       (unless content-type-p
4220         (goto-char (point-min))
4221         (re-search-forward "^MIME-Version:")
4222         (forward-line 1)
4223         (insert "Content-Type: text/plain; charset=us-ascii\n")))))
4224
4225 (defun message-read-from-minibuffer (prompt)
4226   "Read from the minibuffer while providing abbrev expansion."
4227   (if (fboundp 'mail-abbrevs-setup)
4228       (let ((mail-abbrev-mode-regexp "")
4229             (minibuffer-setup-hook 'mail-abbrevs-setup))
4230         (read-from-minibuffer prompt)))
4231   (let ((minibuffer-setup-hook 'mail-abbrev-minibuffer-setup-hook))
4232     (read-string prompt)))
4233
4234 (provide 'message)
4235
4236 (run-hooks 'message-load-hook)
4237
4238 ;;; message.el ends here