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