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