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