1e66446e5025e87a75c44bd209bdf50f8b8cb244
[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 'gnus-group-name-decode "gnus-group")
1138   (autoload 'gnus-groups-from-server "gnus")
1139   (autoload 'rmail-output "rmailout"))
1140
1141 \f
1142
1143 ;;;
1144 ;;; Utility functions.
1145 ;;;
1146
1147 (defmacro message-y-or-n-p (question show &rest text)
1148   "Ask QUESTION, displaying remaining args in a temporary buffer if SHOW."
1149   `(message-talkative-question 'y-or-n-p ,question ,show ,@text))
1150
1151 (defmacro message-delete-line (&optional n)
1152   "Delete the current line (and the next N lines)."
1153   `(delete-region (progn (beginning-of-line) (point))
1154                   (progn (forward-line ,(or n 1)) (point))))
1155
1156 (defun message-unquote-tokens (elems)
1157   "Remove double quotes (\") from strings in list ELEMS."
1158   (mapcar (lambda (item)
1159             (while (string-match "^\\(.*\\)\"\\(.*\\)$" item)
1160               (setq item (concat (match-string 1 item)
1161                                  (match-string 2 item))))
1162             item)
1163           elems))
1164
1165 (defun message-tokenize-header (header &optional separator)
1166   "Split HEADER into a list of header elements.
1167 SEPARATOR is a string of characters to be used as separators.  \",\"
1168 is used by default."
1169   (if (not header)
1170       nil
1171     (let ((regexp (format "[%s]+" (or separator ",")))
1172           (beg 1)
1173           (first t)
1174           quoted elems paren)
1175       (save-excursion
1176         (message-set-work-buffer)
1177         (insert header)
1178         (goto-char (point-min))
1179         (while (not (eobp))
1180           (if first
1181               (setq first nil)
1182             (forward-char 1))
1183           (cond ((and (> (point) beg)
1184                       (or (eobp)
1185                           (and (looking-at regexp)
1186                                (not quoted)
1187                                (not paren))))
1188                  (push (buffer-substring beg (point)) elems)
1189                  (setq beg (match-end 0)))
1190                 ((eq (char-after) ?\")
1191                  (setq quoted (not quoted)))
1192                 ((and (eq (char-after) ?\()
1193                       (not quoted))
1194                  (setq paren t))
1195                 ((and (eq (char-after) ?\))
1196                       (not quoted))
1197                  (setq paren nil))))
1198         (nreverse elems)))))
1199
1200 (defun message-mail-file-mbox-p (file)
1201   "Say whether FILE looks like a Unix mbox file."
1202   (when (and (file-exists-p file)
1203              (file-readable-p file)
1204              (file-regular-p file))
1205     (with-temp-buffer
1206       (nnheader-insert-file-contents file)
1207       (goto-char (point-min))
1208       (looking-at message-unix-mail-delimiter))))
1209
1210 (defun message-fetch-field (header &optional not-all)
1211   "The same as `mail-fetch-field', only remove all newlines."
1212   (let* ((inhibit-point-motion-hooks t)
1213          (case-fold-search t)
1214          (value (mail-fetch-field header nil (not not-all))))
1215     (when value
1216       (while (string-match "\n[\t ]+" value)
1217         (setq value (replace-match " " t t value)))
1218       (set-text-properties 0 (length value) nil value)
1219       value)))
1220
1221 (defun message-narrow-to-field ()
1222   "Narrow the buffer to the header on the current line."
1223   (beginning-of-line)
1224   (narrow-to-region
1225    (point)
1226    (progn
1227      (forward-line 1)
1228      (if (re-search-forward "^[^ \n\t]" nil t)
1229          (progn
1230            (beginning-of-line)
1231            (point))
1232        (point-max))))
1233   (goto-char (point-min)))
1234
1235 (defun message-add-header (&rest headers)
1236   "Add the HEADERS to the message header, skipping those already present."
1237   (while headers
1238     (let (hclean)
1239       (unless (string-match "^\\([^:]+\\):[ \t]*[^ \t]" (car headers))
1240         (error "Invalid header `%s'" (car headers)))
1241       (setq hclean (match-string 1 (car headers)))
1242       (save-restriction
1243         (message-narrow-to-headers)
1244         (unless (re-search-forward (concat "^" (regexp-quote hclean) ":") nil t)
1245           (goto-char (point-max))
1246           (if (string-match "\n$" (car headers))
1247               (insert (car headers))
1248             (insert (car headers) ?\n)))))
1249     (setq headers (cdr headers))))
1250
1251
1252 (defun message-fetch-reply-field (header)
1253   "Fetch field HEADER from the message we're replying to."
1254   (when (and message-reply-buffer
1255              (buffer-name message-reply-buffer))
1256     (save-excursion
1257       (set-buffer message-reply-buffer)
1258       (message-fetch-field header))))
1259
1260 (defun message-set-work-buffer ()
1261   (if (get-buffer " *message work*")
1262       (progn
1263         (set-buffer " *message work*")
1264         (erase-buffer))
1265     (set-buffer (get-buffer-create " *message work*"))
1266     (kill-all-local-variables)
1267     (mm-enable-multibyte)))
1268
1269 (defun message-functionp (form)
1270   "Return non-nil if FORM is funcallable."
1271   (or (and (symbolp form) (fboundp form))
1272       (and (listp form) (eq (car form) 'lambda))
1273       (byte-code-function-p form)))
1274
1275 (defun message-strip-list-identifiers (subject)
1276   "Remove list identifiers in `gnus-list-identifiers' from string SUBJECT."
1277   (require 'gnus-sum)                   ; for gnus-list-identifiers
1278   (let ((regexp (if (stringp gnus-list-identifiers)
1279                     gnus-list-identifiers
1280                   (mapconcat 'identity gnus-list-identifiers " *\\|"))))
1281     (if (string-match (concat "\\(\\(\\(Re: +\\)?\\(" regexp
1282                               " *\\)\\)+\\(Re: +\\)?\\)") subject)
1283         (concat (substring subject 0 (match-beginning 1))
1284                 (or (match-string 3 subject)
1285                     (match-string 5 subject))
1286                 (substring subject
1287                            (match-end 1)))
1288       subject)))
1289
1290 (defun message-strip-subject-re (subject)
1291   "Remove \"Re:\" from subject lines in string SUBJECT."
1292   (if (string-match message-subject-re-regexp subject)
1293       (substring subject (match-end 0))
1294     subject))
1295
1296 (defun message-remove-header (header &optional is-regexp first reverse)
1297   "Remove HEADER in the narrowed buffer.
1298 If IS-REGEXP, HEADER is a regular expression.
1299 If FIRST, only remove the first instance of the header.
1300 Return the number of headers removed."
1301   (goto-char (point-min))
1302   (let ((regexp (if is-regexp header (concat "^" (regexp-quote header) ":")))
1303         (number 0)
1304         (case-fold-search t)
1305         last)
1306     (while (and (not (eobp))
1307                 (not last))
1308       (if (if reverse
1309               (not (looking-at regexp))
1310             (looking-at regexp))
1311           (progn
1312             (incf number)
1313             (when first
1314               (setq last t))
1315             (delete-region
1316              (point)
1317              ;; There might be a continuation header, so we have to search
1318              ;; until we find a new non-continuation line.
1319              (progn
1320                (forward-line 1)
1321                (if (re-search-forward "^[^ \t]" nil t)
1322                    (goto-char (match-beginning 0))
1323                  (point-max)))))
1324         (forward-line 1)
1325         (if (re-search-forward "^[^ \t]" nil t)
1326             (goto-char (match-beginning 0))
1327           (goto-char (point-max)))))
1328     number))
1329
1330 (defun message-remove-first-header (header)
1331   "Remove the first instance of HEADER if there is more than one."
1332   (let ((count 0)
1333         (regexp (concat "^" (regexp-quote header) ":")))
1334     (save-excursion
1335       (goto-char (point-min))
1336       (while (re-search-forward regexp nil t)
1337         (incf count)))
1338     (while (> count 1)
1339       (message-remove-header header nil t)
1340       (decf count))))
1341
1342 (defun message-narrow-to-headers ()
1343   "Narrow the buffer to the head of the message."
1344   (widen)
1345   (narrow-to-region
1346    (goto-char (point-min))
1347    (if (re-search-forward
1348         (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
1349        (match-beginning 0)
1350      (point-max)))
1351   (goto-char (point-min)))
1352
1353 (defun message-narrow-to-head-1 ()
1354   "Like `message-narrow-to-head'.  Don't widen."
1355   (narrow-to-region
1356    (goto-char (point-min))
1357    (if (search-forward "\n\n" nil 1)
1358        (1- (point))
1359      (point-max)))
1360   (goto-char (point-min)))
1361
1362 (defun message-narrow-to-head ()
1363   "Narrow the buffer to the head of the message.
1364 Point is left at the beginning of the narrowed-to region."
1365   (widen)
1366   (message-narrow-to-head-1))
1367
1368 (defun message-narrow-to-headers-or-head ()
1369   "Narrow the buffer to the head of the message."
1370   (widen)
1371   (narrow-to-region
1372    (goto-char (point-min))
1373    (cond
1374     ((re-search-forward
1375       (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
1376      (match-beginning 0))
1377     ((search-forward "\n\n" nil t)
1378      (1- (point)))
1379     (t
1380      (point-max))))
1381   (goto-char (point-min)))
1382
1383 (defun message-news-p ()
1384   "Say whether the current buffer contains a news message."
1385   (and (not message-this-is-mail)
1386        (or message-this-is-news
1387            (save-excursion
1388              (save-restriction
1389                (message-narrow-to-headers)
1390                (and (message-fetch-field "newsgroups")
1391                     (not (message-fetch-field "posted-to"))))))))
1392
1393 (defun message-mail-p ()
1394   "Say whether the current buffer contains a mail message."
1395   (and (not message-this-is-news)
1396        (or message-this-is-mail
1397            (save-excursion
1398              (save-restriction
1399                (message-narrow-to-headers)
1400                (or (message-fetch-field "to")
1401                    (message-fetch-field "cc")
1402                    (message-fetch-field "bcc")))))))
1403
1404 (defun message-next-header ()
1405   "Go to the beginning of the next header."
1406   (beginning-of-line)
1407   (or (eobp) (forward-char 1))
1408   (not (if (re-search-forward "^[^ \t]" nil t)
1409            (beginning-of-line)
1410          (goto-char (point-max)))))
1411
1412 (defun message-sort-headers-1 ()
1413   "Sort the buffer as headers using `message-rank' text props."
1414   (goto-char (point-min))
1415   (require 'sort)
1416   (sort-subr
1417    nil 'message-next-header
1418    (lambda ()
1419      (message-next-header)
1420      (unless (bobp)
1421        (forward-char -1)))
1422    (lambda ()
1423      (or (get-text-property (point) 'message-rank)
1424          10000))))
1425
1426 (defun message-sort-headers ()
1427   "Sort the headers of the current message according to `message-header-format-alist'."
1428   (interactive)
1429   (save-excursion
1430     (save-restriction
1431       (let ((max (1+ (length message-header-format-alist)))
1432             rank)
1433         (message-narrow-to-headers)
1434         (while (re-search-forward "^[^ \n]+:" nil t)
1435           (put-text-property
1436            (match-beginning 0) (1+ (match-beginning 0))
1437            'message-rank
1438            (if (setq rank (length (memq (assq (intern (buffer-substring
1439                                                        (match-beginning 0)
1440                                                        (1- (match-end 0))))
1441                                               message-header-format-alist)
1442                                         message-header-format-alist)))
1443                (- max rank)
1444              (1+ max)))))
1445       (message-sort-headers-1))))
1446
1447 \f
1448
1449 ;;;
1450 ;;; Message mode
1451 ;;;
1452
1453 ;;; Set up keymap.
1454
1455 (defvar message-mode-map nil)
1456
1457 (unless message-mode-map
1458   (setq message-mode-map (make-keymap))
1459   (set-keymap-parent message-mode-map text-mode-map)
1460   (define-key message-mode-map "\C-c?" 'describe-mode)
1461
1462   (define-key message-mode-map "\C-c\C-f\C-t" 'message-goto-to)
1463   (define-key message-mode-map "\C-c\C-f\C-b" 'message-goto-bcc)
1464   (define-key message-mode-map "\C-c\C-f\C-w" 'message-goto-fcc)
1465   (define-key message-mode-map "\C-c\C-f\C-c" 'message-goto-cc)
1466   (define-key message-mode-map "\C-c\C-f\C-s" 'message-goto-subject)
1467   (define-key message-mode-map "\C-c\C-f\C-r" 'message-goto-reply-to)
1468   (define-key message-mode-map "\C-c\C-f\C-n" 'message-goto-newsgroups)
1469   (define-key message-mode-map "\C-c\C-f\C-d" 'message-goto-distribution)
1470   (define-key message-mode-map "\C-c\C-f\C-f" 'message-goto-followup-to)
1471   (define-key message-mode-map "\C-c\C-f\C-k" 'message-goto-keywords)
1472   (define-key message-mode-map "\C-c\C-f\C-u" 'message-goto-summary)
1473   (define-key message-mode-map "\C-c\C-b" 'message-goto-body)
1474   (define-key message-mode-map "\C-c\C-i" 'message-goto-signature)
1475
1476   (define-key message-mode-map "\C-c\C-t" 'message-insert-to)
1477   (define-key message-mode-map "\C-c\C-n" 'message-insert-newsgroups)
1478
1479   (define-key message-mode-map "\C-c\C-y" 'message-yank-original)
1480   (define-key message-mode-map "\C-c\M-\C-y" 'message-yank-buffer)
1481   (define-key message-mode-map "\C-c\C-q" 'message-fill-yanked-message)
1482   (define-key message-mode-map "\C-c\C-w" 'message-insert-signature)
1483   (define-key message-mode-map "\C-c\M-h" 'message-insert-headers)
1484   (define-key message-mode-map "\C-c\C-r" 'message-caesar-buffer-body)
1485   (define-key message-mode-map "\C-c\C-o" 'message-sort-headers)
1486   (define-key message-mode-map "\C-c\M-r" 'message-rename-buffer)
1487
1488   (define-key message-mode-map "\C-c\C-c" 'message-send-and-exit)
1489   (define-key message-mode-map "\C-c\C-s" 'message-send)
1490   (define-key message-mode-map "\C-c\C-k" 'message-kill-buffer)
1491   (define-key message-mode-map "\C-c\C-d" 'message-dont-send)
1492   (define-key message-mode-map "\C-c\n" 'gnus-delay-article)
1493
1494   (define-key message-mode-map "\C-c\C-e" 'message-elide-region)
1495   (define-key message-mode-map "\C-c\C-v" 'message-delete-not-region)
1496   (define-key message-mode-map "\C-c\C-z" 'message-kill-to-signature)
1497   (define-key message-mode-map "\M-\r" 'message-newline-and-reformat)
1498   ;;(define-key message-mode-map "\M-q" 'message-fill-paragraph)
1499
1500   (define-key message-mode-map "\C-c\C-a" 'mml-attach-file)
1501
1502   (define-key message-mode-map "\t" 'message-tab)
1503   (define-key message-mode-map "\M-;" 'comment-region))
1504
1505 (easy-menu-define
1506   message-mode-menu message-mode-map "Message Menu."
1507   `("Message"
1508     ["Sort Headers" message-sort-headers t]
1509     ["Yank Original" message-yank-original t]
1510     ["Fill Yanked Message" message-fill-yanked-message t]
1511     ["Insert Signature" message-insert-signature t]
1512     ["Caesar (rot13) Message" message-caesar-buffer-body t]
1513     ["Caesar (rot13) Region" message-caesar-region (mark t)]
1514     ["Elide Region" message-elide-region (mark t)]
1515     ["Delete Outside Region" message-delete-not-region (mark t)]
1516     ["Kill To Signature" message-kill-to-signature t]
1517     ["Newline and Reformat" message-newline-and-reformat t]
1518     ["Rename buffer" message-rename-buffer t]
1519     ["Spellcheck" ispell-message
1520      ,@(if (featurep 'xemacs) '(t)
1521          '(:help "Spellcheck this message"))]
1522     "----"
1523     ["Send Message" message-send-and-exit
1524      ,@(if (featurep 'xemacs) '(t)
1525          '(:help "Send this message"))]
1526     ["Postpone Message" message-dont-send
1527      ,@(if (featurep 'xemacs) '(t)
1528          '(:help "File this draft message and exit"))]
1529     ["Send at Specific Time" gnus-delay-article
1530      ,@(if (featurep 'xemacs) '(t)
1531          '(:help "Ask, then arrange to send message at that time"))]
1532     ["Kill Message" message-kill-buffer
1533      ,@(if (featurep 'xemacs) '(t)
1534          '(:help "Delete this message without sending"))]))
1535
1536 (easy-menu-define
1537   message-mode-field-menu message-mode-map ""
1538   '("Field"
1539     ["Fetch To" message-insert-to t]
1540     ["Fetch Newsgroups" message-insert-newsgroups t]
1541     "----"
1542     ["To" message-goto-to t]
1543     ["Subject" message-goto-subject t]
1544     ["Cc" message-goto-cc t]
1545     ["Reply-To" message-goto-reply-to t]
1546     ["Summary" message-goto-summary t]
1547     ["Keywords" message-goto-keywords t]
1548     ["Newsgroups" message-goto-newsgroups t]
1549     ["Followup-To" message-goto-followup-to t]
1550     ["Distribution" message-goto-distribution t]
1551     ["Body" message-goto-body t]
1552     ["Signature" message-goto-signature t]))
1553
1554 (defvar message-tool-bar-map nil)
1555
1556 (eval-when-compile
1557   (defvar facemenu-add-face-function)
1558   (defvar facemenu-remove-face-function))
1559
1560 ;;;###autoload
1561 (define-derived-mode message-mode text-mode "Message"
1562   "Major mode for editing mail and news to be sent.
1563 Like Text Mode but with these additional commands:\\<message-mode-map>
1564 C-c C-s  `message-send' (send the message)  C-c C-c  `message-send-and-exit'
1565 C-c C-d  Postpone sending the message       C-c C-k  Kill the message
1566 C-c C-f  move to a header field (and create it if there isn't):
1567          C-c C-f C-t  move to To        C-c C-f C-s  move to Subject
1568          C-c C-f C-c  move to Cc        C-c C-f C-b  move to Bcc
1569          C-c C-f C-w  move to Fcc       C-c C-f C-r  move to Reply-To
1570          C-c C-f C-u  move to Summary   C-c C-f C-n  move to Newsgroups
1571          C-c C-f C-k  move to Keywords  C-c C-f C-d  move to Distribution
1572          C-c C-f C-f  move to Followup-To
1573 C-c C-t  `message-insert-to' (add a To header to a news followup)
1574 C-c C-n  `message-insert-newsgroups' (add a Newsgroup header to a news reply)
1575 C-c C-b  `message-goto-body' (move to beginning of message text).
1576 C-c C-i  `message-goto-signature' (move to the beginning of the signature).
1577 C-c C-w  `message-insert-signature' (insert `message-signature-file' file).
1578 C-c C-y  `message-yank-original' (insert current message, if any).
1579 C-c C-q  `message-fill-yanked-message' (fill what was yanked).
1580 C-c C-e  `message-elide-region' (elide the text between point and mark).
1581 C-c C-v  `message-delete-not-region' (remove the text outside the region).
1582 C-c C-z  `message-kill-to-signature' (kill the text up to the signature).
1583 C-c C-r  `message-caesar-buffer-body' (rot13 the message body).
1584 C-c C-a  `mml-attach-file' (attach a file as MIME).
1585 M-RET    `message-newline-and-reformat' (break the line and reformat)."
1586   (set (make-local-variable 'message-reply-buffer) nil)
1587   (make-local-variable 'message-send-actions)
1588   (make-local-variable 'message-exit-actions)
1589   (make-local-variable 'message-kill-actions)
1590   (make-local-variable 'message-postpone-actions)
1591   (make-local-variable 'message-draft-article)
1592   (setq buffer-offer-save t)
1593   (set (make-local-variable 'facemenu-add-face-function)
1594        (lambda (face end)
1595          (let ((face-fun (cdr (assq face message-face-alist))))
1596            (if face-fun
1597                (funcall face-fun (point) end)
1598              (error "Face %s not configured for %s mode" face mode-name)))
1599          ""))
1600   (set (make-local-variable 'facemenu-remove-face-function) t)
1601   (set (make-local-variable 'message-reply-headers) nil)
1602   (make-local-variable 'message-newsreader)
1603   (make-local-variable 'message-mailer)
1604   (make-local-variable 'message-post-method)
1605   (set (make-local-variable 'message-sent-message-via) nil)
1606   (set (make-local-variable 'message-checksum) nil)
1607   (set (make-local-variable 'message-mime-part) 0)
1608   (message-setup-fill-variables)
1609   ;; Allow using comment commands to add/remove quoting.
1610   (set (make-local-variable 'comment-start) message-yank-prefix)
1611   (if (featurep 'xemacs)
1612       (message-setup-toolbar)
1613     (set (make-local-variable 'font-lock-defaults)
1614          '(message-font-lock-keywords t))
1615     (if (boundp 'tool-bar-map)
1616         (set (make-local-variable 'tool-bar-map) (message-tool-bar-map))))
1617   (easy-menu-add message-mode-menu message-mode-map)
1618   (easy-menu-add message-mode-field-menu message-mode-map)
1619   ;; Allow mail alias things.
1620   (when (eq message-mail-alias-type 'abbrev)
1621     (if (fboundp 'mail-abbrevs-setup)
1622         (mail-abbrevs-setup)
1623       (mail-aliases-setup)))
1624   (message-set-auto-save-file-name)
1625   (mm-enable-multibyte)
1626   (set (make-local-variable 'indent-tabs-mode) nil) ;No tabs for indentation.
1627   (mml-mode))
1628
1629 (defun message-setup-fill-variables ()
1630   "Setup message fill variables."
1631   (set (make-local-variable 'fill-paragraph-function)
1632        'message-fill-paragraph)
1633   (make-local-variable 'paragraph-separate)
1634   (make-local-variable 'paragraph-start)
1635   (make-local-variable 'adaptive-fill-regexp)
1636   (unless (boundp 'adaptive-fill-first-line-regexp)
1637     (setq adaptive-fill-first-line-regexp nil))
1638   (make-local-variable 'adaptive-fill-first-line-regexp)
1639   (make-local-variable 'auto-fill-inhibit-regexp)
1640   (make-local-variable 'normal-auto-fill-function)
1641   (let ((quote-prefix-regexp
1642          ;; User should change message-cite-prefix-regexp if
1643          ;; message-yank-prefix is set to an abnormal value.
1644          (concat "\\(" message-cite-prefix-regexp "\\)[ \t]*")))
1645     (setq paragraph-start
1646           (concat
1647            (regexp-quote mail-header-separator) "$\\|"
1648            "[ \t]*$\\|"                 ; blank lines
1649            "-- $\\|"                    ; signature delimiter
1650            "---+$\\|"              ; delimiters for forwarded messages
1651            page-delimiter "$\\|"        ; spoiler warnings
1652            ".*wrote:$\\|"               ; attribution lines
1653            quote-prefix-regexp "$"))    ; empty lines in quoted text
1654     (setq paragraph-separate paragraph-start)
1655     (setq adaptive-fill-regexp
1656           (concat quote-prefix-regexp "\\|" adaptive-fill-regexp))
1657     (setq adaptive-fill-first-line-regexp
1658           (concat quote-prefix-regexp "\\|"
1659                   adaptive-fill-first-line-regexp))
1660     ;;(setq auto-fill-inhibit-regexp "^[A-Z][^: \n\t]+:")
1661     (setq auto-fill-inhibit-regexp nil)
1662     (setq normal-auto-fill-function 'message-do-auto-fill)))
1663
1664 \f
1665
1666 ;;;
1667 ;;; Message mode commands
1668 ;;;
1669
1670 ;;; Movement commands
1671
1672 (defun message-goto-to ()
1673   "Move point to the To header."
1674   (interactive)
1675   (message-position-on-field "To"))
1676
1677 (defun message-goto-subject ()
1678   "Move point to the Subject header."
1679   (interactive)
1680   (message-position-on-field "Subject"))
1681
1682 (defun message-goto-cc ()
1683   "Move point to the Cc header."
1684   (interactive)
1685   (message-position-on-field "Cc" "To"))
1686
1687 (defun message-goto-bcc ()
1688   "Move point to the Bcc  header."
1689   (interactive)
1690   (message-position-on-field "Bcc" "Cc" "To"))
1691
1692 (defun message-goto-fcc ()
1693   "Move point to the Fcc header."
1694   (interactive)
1695   (message-position-on-field "Fcc" "To" "Newsgroups"))
1696
1697 (defun message-goto-reply-to ()
1698   "Move point to the Reply-To header."
1699   (interactive)
1700   (message-position-on-field "Reply-To" "Subject"))
1701
1702 (defun message-goto-newsgroups ()
1703   "Move point to the Newsgroups header."
1704   (interactive)
1705   (message-position-on-field "Newsgroups"))
1706
1707 (defun message-goto-distribution ()
1708   "Move point to the Distribution header."
1709   (interactive)
1710   (message-position-on-field "Distribution"))
1711
1712 (defun message-goto-followup-to ()
1713   "Move point to the Followup-To header."
1714   (interactive)
1715   (message-position-on-field "Followup-To" "Newsgroups"))
1716
1717 (defun message-goto-keywords ()
1718   "Move point to the Keywords header."
1719   (interactive)
1720   (message-position-on-field "Keywords" "Subject"))
1721
1722 (defun message-goto-summary ()
1723   "Move point to the Summary header."
1724   (interactive)
1725   (message-position-on-field "Summary" "Subject"))
1726
1727 (defun message-goto-body (&optional interactivep)
1728   "Move point to the beginning of the message body."
1729   (interactive (list t))
1730   (when (and interactivep
1731              (looking-at "[ \t]*\n"))
1732     (expand-abbrev))
1733   (goto-char (point-min))
1734   (or (search-forward (concat "\n" mail-header-separator "\n") nil t)
1735       (search-forward-regexp "[^:]+:\\([^\n]\\|\n[ \t]\\)+\n\n" nil t)))
1736
1737 (defun message-goto-eoh ()
1738   "Move point to the end of the headers."
1739   (interactive)
1740   (message-goto-body)
1741   (forward-line -1))
1742
1743 (defun message-goto-signature ()
1744   "Move point to the beginning of the message signature.
1745 If there is no signature in the article, go to the end and
1746 return nil."
1747   (interactive)
1748   (goto-char (point-min))
1749   (if (re-search-forward message-signature-separator nil t)
1750       (forward-line 1)
1751     (goto-char (point-max))
1752     nil))
1753
1754 \f
1755
1756 (defun message-insert-to (&optional force)
1757   "Insert a To header that points to the author of the article being replied to.
1758 If the original author requested not to be sent mail, the function signals
1759 an error.
1760 With the prefix argument FORCE, insert the header anyway."
1761   (interactive "P")
1762   (let ((co (message-fetch-reply-field "mail-copies-to")))
1763     (when (and (null force)
1764                co
1765                (or (equal (downcase co) "never")
1766                    (equal (downcase co) "nobody")))
1767       (error "The user has requested not to have copies sent via mail")))
1768   (when (and (message-position-on-field "To")
1769              (mail-fetch-field "to")
1770              (not (string-match "\\` *\\'" (mail-fetch-field "to"))))
1771     (insert ", "))
1772   (insert (or (message-fetch-reply-field "mail-reply-to")
1773               (message-fetch-reply-field "reply-to")
1774               (message-fetch-reply-field "from") "")))
1775
1776 (defun message-widen-reply ()
1777   "Widen the reply to include maximum recipients."
1778   (interactive)
1779   (let ((follow-to
1780          (and message-reply-buffer
1781               (buffer-name message-reply-buffer)
1782               (save-excursion
1783                 (set-buffer message-reply-buffer)
1784                 (message-get-reply-headers t)))))
1785     (save-excursion
1786       (save-restriction
1787         (message-narrow-to-headers)
1788         (dolist (elem follow-to)
1789           (message-remove-header (symbol-name (car elem)))
1790           (goto-char (point-min))
1791           (insert (symbol-name (car elem)) ": "
1792                   (cdr elem) "\n"))))))
1793
1794 (defun message-insert-newsgroups ()
1795   "Insert the Newsgroups header from the article being replied to."
1796   (interactive)
1797   (when (and (message-position-on-field "Newsgroups")
1798              (mail-fetch-field "newsgroups")
1799              (not (string-match "\\` *\\'" (mail-fetch-field "newsgroups"))))
1800     (insert ","))
1801   (insert (or (message-fetch-reply-field "newsgroups") "")))
1802
1803 \f
1804
1805 ;;; Various commands
1806
1807 (defun message-delete-not-region (beg end)
1808   "Delete everything in the body of the current message outside of the region."
1809   (interactive "r")
1810   (let (citeprefix)
1811     (save-excursion
1812       (goto-char beg)
1813       ;; snarf citation prefix, if appropriate
1814       (unless (eq (point) (progn (beginning-of-line) (point)))
1815         (when (looking-at message-cite-prefix-regexp)
1816           (setq citeprefix (match-string 0))))
1817       (goto-char end)
1818       (delete-region (point) (if (not (message-goto-signature))
1819                                  (point)
1820                                (forward-line -2)
1821                                (point)))
1822       (insert "\n")
1823       (goto-char beg)
1824       (delete-region beg (progn (message-goto-body)
1825                                 (forward-line 2)
1826                                 (point)))
1827       (when citeprefix
1828         (insert citeprefix))))
1829   (when (message-goto-signature)
1830     (forward-line -2)))
1831
1832 (defun message-kill-to-signature ()
1833   "Deletes all text up to the signature."
1834   (interactive)
1835   (let ((point (point)))
1836     (message-goto-signature)
1837     (unless (eobp)
1838       (forward-line -2))
1839     (kill-region point (point))
1840     (unless (bolp)
1841       (insert "\n"))))
1842
1843 (defun message-newline-and-reformat (&optional arg not-break)
1844   "Insert four newlines, and then reformat if inside quoted text.
1845 Prefix arg means justify as well."
1846   (interactive (list (if current-prefix-arg 'full)))
1847   (let (quoted point beg end leading-space bolp)
1848     (setq point (point))
1849     (beginning-of-line)
1850     (setq beg (point))
1851     (setq bolp (= beg point))
1852     ;; Find first line of the paragraph.
1853     (if not-break
1854         (while (and (not (eobp))
1855                     (not (looking-at message-cite-prefix-regexp))
1856                     (looking-at paragraph-start))
1857           (forward-line 1)))
1858     ;; Find the prefix
1859     (when (looking-at message-cite-prefix-regexp)
1860       (setq quoted (match-string 0))
1861       (goto-char (match-end 0))
1862       (looking-at "[ \t]*")
1863       (setq leading-space (match-string 0)))
1864     (if (and quoted
1865              (not not-break)
1866              (not bolp)
1867              (< (- point beg) (length quoted)))
1868         ;; break inside the cite prefix.
1869         (setq quoted nil
1870               end nil))
1871     (if quoted
1872         (progn
1873           (forward-line 1)
1874           (while (and (not (eobp))
1875                       (not (looking-at paragraph-separate))
1876                       (looking-at message-cite-prefix-regexp)
1877                       (equal quoted (match-string 0)))
1878             (goto-char (match-end 0))
1879             (looking-at "[ \t]*")
1880             (if (> (length leading-space) (length (match-string 0)))
1881                 (setq leading-space (match-string 0)))
1882             (forward-line 1))
1883           (setq end (point))
1884           (goto-char beg)
1885           (while (and (if (bobp) nil (forward-line -1) t)
1886                       (not (looking-at paragraph-start))
1887                       (looking-at message-cite-prefix-regexp)
1888                       (equal quoted (match-string 0)))
1889             (setq beg (point))
1890             (goto-char (match-end 0))
1891             (looking-at "[ \t]*")
1892             (if (> (length leading-space) (length (match-string 0)))
1893                 (setq leading-space (match-string 0)))))
1894       (while (and (not (eobp))
1895                   (not (looking-at paragraph-separate))
1896                   (not (looking-at message-cite-prefix-regexp)))
1897         (forward-line 1))
1898       (setq end (point))
1899       (goto-char beg)
1900       (while (and (if (bobp) nil (forward-line -1) t)
1901                   (not (looking-at paragraph-start))
1902                   (not (looking-at message-cite-prefix-regexp)))
1903         (setq beg (point))))
1904     (goto-char point)
1905     (save-restriction
1906       (narrow-to-region beg end)
1907       (if not-break
1908           (setq point nil)
1909         (if bolp
1910             (insert "\n")
1911           (insert "\n\n"))
1912         (setq point (point))
1913         (insert "\n\n")
1914         (delete-region (point) (re-search-forward "[ \t]*"))
1915         (when (and quoted (not bolp))
1916           (insert quoted leading-space)))
1917       (if quoted
1918           (let* ((adaptive-fill-regexp
1919                   (regexp-quote (concat quoted leading-space)))
1920                  (adaptive-fill-first-line-regexp
1921                   adaptive-fill-regexp ))
1922             (fill-paragraph arg))
1923         (fill-paragraph arg))
1924       (if point (goto-char point)))))
1925
1926 (defun message-fill-paragraph (&optional arg)
1927   "Like `fill-paragraph'."
1928   (interactive (list (if current-prefix-arg 'full)))
1929   (if (and (boundp 'filladapt-mode) filladapt-mode)
1930       nil
1931     (message-newline-and-reformat arg t)
1932     t))
1933
1934 (defun message-do-auto-fill ()
1935   "Like `do-auto-fill', but don't fill in message header."
1936   (unless (text-property-any (gnus-point-at-bol) (point)
1937                              'message-field 'header)
1938     (do-auto-fill)))
1939
1940 (defun message-insert-signature (&optional force)
1941   "Insert a signature.  See documentation for variable `message-signature'."
1942   (interactive (list 0))
1943   (let* ((signature
1944           (cond
1945            ((and (null message-signature)
1946                  (eq force 0))
1947             (save-excursion
1948               (goto-char (point-max))
1949               (not (re-search-backward message-signature-separator nil t))))
1950            ((and (null message-signature)
1951                  force)
1952             t)
1953            ((message-functionp message-signature)
1954             (funcall message-signature))
1955            ((listp message-signature)
1956             (eval message-signature))
1957            (t message-signature)))
1958          (signature
1959           (cond ((stringp signature)
1960                  signature)
1961                 ((and (eq t signature)
1962                       message-signature-file
1963                       (file-exists-p message-signature-file))
1964                  signature))))
1965     (when signature
1966       (goto-char (point-max))
1967       ;; Insert the signature.
1968       (unless (bolp)
1969         (insert "\n"))
1970       (insert "\n-- \n")
1971       (if (eq signature t)
1972           (insert-file-contents message-signature-file)
1973         (insert signature))
1974       (goto-char (point-max))
1975       (or (bolp) (insert "\n")))))
1976
1977 (defun message-elide-region (b e)
1978   "Elide the text in the region.
1979 An ellipsis (from `message-elide-ellipsis') will be inserted where the
1980 text was killed."
1981   (interactive "r")
1982   (kill-region b e)
1983   (insert message-elide-ellipsis))
1984
1985 (defvar message-caesar-translation-table nil)
1986
1987 (defun message-caesar-region (b e &optional n)
1988   "Caesar rotate region B to E by N, default 13, for decrypting netnews."
1989   (interactive
1990    (list
1991     (min (point) (or (mark t) (point)))
1992     (max (point) (or (mark t) (point)))
1993     (when current-prefix-arg
1994       (prefix-numeric-value current-prefix-arg))))
1995
1996   (setq n (if (numberp n) (mod n 26) 13)) ;canonize N
1997   (unless (or (zerop n)                 ; no action needed for a rot of 0
1998               (= b e))                  ; no region to rotate
1999     ;; We build the table, if necessary.
2000     (when (or (not message-caesar-translation-table)
2001               (/= (aref message-caesar-translation-table ?a) (+ ?a n)))
2002       (setq message-caesar-translation-table
2003             (message-make-caesar-translation-table n)))
2004     (translate-region b e message-caesar-translation-table)))
2005
2006 (defun message-make-caesar-translation-table (n)
2007   "Create a rot table with offset N."
2008   (let ((i -1)
2009         (table (make-string 256 0)))
2010     (while (< (incf i) 256)
2011       (aset table i i))
2012     (concat
2013      (substring table 0 ?A)
2014      (substring table (+ ?A n) (+ ?A n (- 26 n)))
2015      (substring table ?A (+ ?A n))
2016      (substring table (+ ?A 26) ?a)
2017      (substring table (+ ?a n) (+ ?a n (- 26 n)))
2018      (substring table ?a (+ ?a n))
2019      (substring table (+ ?a 26) 255))))
2020
2021 (defun message-caesar-buffer-body (&optional rotnum)
2022   "Caesar rotate all letters in the current buffer by 13 places.
2023 Used to encode/decode possibly offensive messages (commonly in rec.humor).
2024 With prefix arg, specifies the number of places to rotate each letter forward.
2025 Mail and USENET news headers are not rotated."
2026   (interactive (if current-prefix-arg
2027                    (list (prefix-numeric-value current-prefix-arg))
2028                  (list nil)))
2029   (save-excursion
2030     (save-restriction
2031       (when (message-goto-body)
2032         (narrow-to-region (point) (point-max)))
2033       (message-caesar-region (point-min) (point-max) rotnum))))
2034
2035 (defun message-pipe-buffer-body (program)
2036   "Pipe the message body in the current buffer through PROGRAM."
2037   (save-excursion
2038     (save-restriction
2039       (when (message-goto-body)
2040         (narrow-to-region (point) (point-max)))
2041       (shell-command-on-region
2042        (point-min) (point-max) program nil t))))
2043
2044 (defun message-rename-buffer (&optional enter-string)
2045   "Rename the *message* buffer to \"*message* RECIPIENT\".
2046 If the function is run with a prefix, it will ask for a new buffer
2047 name, rather than giving an automatic name."
2048   (interactive "Pbuffer name: ")
2049   (save-excursion
2050     (save-restriction
2051       (goto-char (point-min))
2052       (narrow-to-region (point)
2053                         (search-forward mail-header-separator nil 'end))
2054       (let* ((mail-to (or
2055                        (if (message-news-p) (message-fetch-field "Newsgroups")
2056                          (message-fetch-field "To"))
2057                        ""))
2058              (mail-trimmed-to
2059               (if (string-match "," mail-to)
2060                   (concat (substring mail-to 0 (match-beginning 0)) ", ...")
2061                 mail-to))
2062              (name-default (concat "*message* " mail-trimmed-to))
2063              (name (if enter-string
2064                        (read-string "New buffer name: " name-default)
2065                      name-default)))
2066         (rename-buffer name t)))))
2067
2068 (defun message-fill-yanked-message (&optional justifyp)
2069   "Fill the paragraphs of a message yanked into this one.
2070 Numeric argument means justify as well."
2071   (interactive "P")
2072   (save-excursion
2073     (goto-char (point-min))
2074     (search-forward (concat "\n" mail-header-separator "\n") nil t)
2075     (let ((fill-prefix message-yank-prefix))
2076       (fill-individual-paragraphs (point) (point-max) justifyp))))
2077
2078 (defun message-indent-citation ()
2079   "Modify text just inserted from a message to be cited.
2080 The inserted text should be the region.
2081 When this function returns, the region is again around the modified text.
2082
2083 Normally, indent each nonblank line `message-indentation-spaces' spaces.
2084 However, if `message-yank-prefix' is non-nil, insert that prefix on each line."
2085   (let ((start (point)))
2086     ;; Remove unwanted headers.
2087     (when message-ignored-cited-headers
2088       (let (all-removed)
2089         (save-restriction
2090           (narrow-to-region
2091            (goto-char start)
2092            (if (search-forward "\n\n" nil t)
2093                (1- (point))
2094              (point)))
2095           (message-remove-header message-ignored-cited-headers t)
2096           (when (= (point-min) (point-max))
2097             (setq all-removed t))
2098           (goto-char (point-max)))
2099         (if all-removed
2100             (goto-char start)
2101           (forward-line 1))))
2102     ;; Delete blank lines at the start of the buffer.
2103     (while (and (point-min)
2104                 (eolp)
2105                 (not (eobp)))
2106       (message-delete-line))
2107     ;; Delete blank lines at the end of the buffer.
2108     (goto-char (point-max))
2109     (unless (eolp)
2110       (insert "\n"))
2111     (while (and (zerop (forward-line -1))
2112                 (looking-at "$"))
2113       (message-delete-line))
2114     ;; Do the indentation.
2115     (if (null message-yank-prefix)
2116         (indent-rigidly start (mark t) message-indentation-spaces)
2117       (save-excursion
2118         (goto-char start)
2119           (while (< (point) (mark t))
2120           (if (looking-at ">")
2121               (insert message-yank-cited-prefix)
2122             (insert message-yank-prefix))
2123           (forward-line 1))))
2124     (goto-char start)))
2125
2126 (defun message-yank-original (&optional arg)
2127   "Insert the message being replied to, if any.
2128 Puts point before the text and mark after.
2129 Normally indents each nonblank line ARG spaces (default 3).  However,
2130 if `message-yank-prefix' is non-nil, insert that prefix on each line.
2131
2132 This function uses `message-cite-function' to do the actual citing.
2133
2134 Just \\[universal-argument] as argument means don't indent, insert no
2135 prefix, and don't delete any headers."
2136   (interactive "P")
2137   (let ((modified (buffer-modified-p)))
2138     (when (and message-reply-buffer
2139                message-cite-function)
2140       (delete-windows-on message-reply-buffer t)
2141       (insert-buffer message-reply-buffer)
2142       (unless arg
2143         (funcall message-cite-function))
2144       (message-exchange-point-and-mark)
2145       (unless (bolp)
2146         (insert ?\n))
2147       (unless modified
2148         (setq message-checksum (message-checksum))))))
2149
2150 (defun message-yank-buffer (buffer)
2151   "Insert BUFFER into the current buffer and quote it."
2152   (interactive "bYank buffer: ")
2153   (let ((message-reply-buffer buffer))
2154     (save-window-excursion
2155       (message-yank-original))))
2156
2157 (defun message-buffers ()
2158   "Return a list of active message buffers."
2159   (let (buffers)
2160     (save-excursion
2161       (dolist (buffer (buffer-list t))
2162         (set-buffer buffer)
2163         (when (and (eq major-mode 'message-mode)
2164                    (null message-sent-message-via))
2165           (push (buffer-name buffer) buffers))))
2166     (nreverse buffers)))
2167
2168 (defun message-cite-original-without-signature ()
2169   "Cite function in the standard Message manner."
2170   (let ((start (point))
2171         (end (mark t))
2172         (functions
2173          (when message-indent-citation-function
2174            (if (listp message-indent-citation-function)
2175                message-indent-citation-function
2176              (list message-indent-citation-function)))))
2177     (mml-quote-region start end)
2178     ;; Allow undoing.
2179     (undo-boundary)
2180     (goto-char end)
2181     (when (re-search-backward message-signature-separator start t)
2182       ;; Also peel off any blank lines before the signature.
2183       (forward-line -1)
2184       (while (looking-at "^[ \t]*$")
2185         (forward-line -1))
2186       (forward-line 1)
2187       (delete-region (point) end)
2188       (unless (search-backward "\n\n" start t)
2189         ;; Insert a blank line if it is peeled off.
2190         (insert "\n")))
2191     (goto-char start)
2192     (while functions
2193       (funcall (pop functions)))
2194     (when message-citation-line-function
2195       (unless (bolp)
2196         (insert "\n"))
2197       (funcall message-citation-line-function))))
2198
2199 (eval-when-compile (defvar mail-citation-hook)) ;Compiler directive
2200 (defun message-cite-original ()
2201   "Cite function in the standard Message manner."
2202   (if (and (boundp 'mail-citation-hook)
2203            mail-citation-hook)
2204       (run-hooks 'mail-citation-hook)
2205     (let ((start (point))
2206           (end (mark t))
2207           (functions
2208            (when message-indent-citation-function
2209              (if (listp message-indent-citation-function)
2210                  message-indent-citation-function
2211                (list message-indent-citation-function)))))
2212       (mml-quote-region start end)
2213       (goto-char start)
2214       (while functions
2215         (funcall (pop functions)))
2216       (when message-citation-line-function
2217         (unless (bolp)
2218           (insert "\n"))
2219         (funcall message-citation-line-function)))))
2220
2221 (defun message-insert-citation-line ()
2222   "Insert a simple citation line."
2223   (when message-reply-headers
2224     (insert (mail-header-from message-reply-headers) " writes:\n\n")))
2225
2226 (defun message-position-on-field (header &rest afters)
2227   (let ((case-fold-search t))
2228     (save-restriction
2229       (narrow-to-region
2230        (goto-char (point-min))
2231        (progn
2232          (re-search-forward
2233           (concat "^" (regexp-quote mail-header-separator) "$"))
2234          (match-beginning 0)))
2235       (goto-char (point-min))
2236       (if (re-search-forward (concat "^" (regexp-quote header) ":") nil t)
2237           (progn
2238             (re-search-forward "^[^ \t]" nil 'move)
2239             (beginning-of-line)
2240             (skip-chars-backward "\n")
2241             t)
2242         (while (and afters
2243                     (not (re-search-forward
2244                           (concat "^" (regexp-quote (car afters)) ":")
2245                           nil t)))
2246           (pop afters))
2247         (when afters
2248           (re-search-forward "^[^ \t]" nil 'move)
2249           (beginning-of-line))
2250         (insert header ": \n")
2251         (forward-char -1)
2252         nil))))
2253
2254 (defun message-remove-signature ()
2255   "Remove the signature from the text between point and mark.
2256 The text will also be indented the normal way."
2257   (save-excursion
2258     (let ((start (point))
2259           mark)
2260       (if (not (re-search-forward message-signature-separator (mark t) t))
2261           ;; No signature here, so we just indent the cited text.
2262           (message-indent-citation)
2263         ;; Find the last non-empty line.
2264         (forward-line -1)
2265         (while (looking-at "[ \t]*$")
2266           (forward-line -1))
2267         (forward-line 1)
2268         (setq mark (set-marker (make-marker) (point)))
2269         (goto-char start)
2270         (message-indent-citation)
2271         ;; Enable undoing the deletion.
2272         (undo-boundary)
2273         (delete-region mark (mark t))
2274         (set-marker mark nil)))))
2275
2276 \f
2277
2278 ;;;
2279 ;;; Sending messages
2280 ;;;
2281
2282 (defun message-send-and-exit (&optional arg)
2283   "Send message like `message-send', then, if no errors, exit from mail buffer."
2284   (interactive "P")
2285   (let ((buf (current-buffer))
2286         (actions message-exit-actions))
2287     (when (and (message-send arg)
2288                (buffer-name buf))
2289       (if message-kill-buffer-on-exit
2290           (kill-buffer buf)
2291         (bury-buffer buf)
2292         (when (eq buf (current-buffer))
2293           (message-bury buf)))
2294       (message-do-actions actions)
2295       t)))
2296
2297 (defun message-dont-send ()
2298   "Don't send the message you have been editing."
2299   (interactive)
2300   (set-buffer-modified-p t)
2301   (save-buffer)
2302   (let ((actions message-postpone-actions))
2303     (message-bury (current-buffer))
2304     (message-do-actions actions)))
2305
2306 (defun message-kill-buffer ()
2307   "Kill the current buffer."
2308   (interactive)
2309   (when (or (not (buffer-modified-p))
2310             (yes-or-no-p "Message modified; kill anyway? "))
2311     (let ((actions message-kill-actions))
2312       (setq buffer-file-name nil)
2313       (kill-buffer (current-buffer))
2314       (message-do-actions actions))))
2315
2316 (defun message-bury (buffer)
2317   "Bury this mail BUFFER."
2318   (let ((newbuf (other-buffer buffer)))
2319     (bury-buffer buffer)
2320     (if (and (fboundp 'frame-parameters)
2321              (cdr (assq 'dedicated (frame-parameters)))
2322              (not (null (delq (selected-frame) (visible-frame-list)))))
2323         (delete-frame (selected-frame))
2324       (switch-to-buffer newbuf))))
2325
2326 (defun message-send (&optional arg)
2327   "Send the message in the current buffer.
2328 If `message-interactive' is non-nil, wait for success indication or
2329 error messages, and inform user.
2330 Otherwise any failure is reported in a message back to the user from
2331 the mailer.
2332 The usage of ARG is defined by the instance that called Message.
2333 It should typically alter the sending method in some way or other."
2334   (interactive "P")
2335   ;; Make it possible to undo the coming changes.
2336   (undo-boundary)
2337   (let ((inhibit-read-only t))
2338     (put-text-property (point-min) (point-max) 'read-only nil))
2339   (message-fix-before-sending)
2340   (run-hooks 'message-send-hook)
2341   (message message-sending-message)
2342   (let ((alist message-send-method-alist)
2343         (success t)
2344         elem sent
2345         (message-options message-options))
2346     (message-options-set-recipient)
2347     (while (and success
2348                 (setq elem (pop alist)))
2349       (when (funcall (cadr elem))
2350         (when (and (or (not (memq (car elem)
2351                                   message-sent-message-via))
2352                        (if (or (message-gnksa-enable-p 'multiple-copies)
2353                                (not (eq (car elem) 'news)))
2354                            (y-or-n-p
2355                             (format
2356                              "Already sent message via %s; resend? "
2357                              (car elem)))
2358                          (error "Denied posting -- multiple copies")))
2359                    (setq success (funcall (caddr elem) arg)))
2360           (setq sent t))))
2361     (unless (or sent (not success))
2362       (error "No methods specified to send by"))
2363     (when (and success sent)
2364       (message-do-fcc)
2365       (save-excursion
2366         (run-hooks 'message-sent-hook))
2367       (message "Sending...done")
2368       ;; Mark the buffer as unmodified and delete auto-save.
2369       (set-buffer-modified-p nil)
2370       (delete-auto-save-file-if-necessary t)
2371       (message-disassociate-draft)
2372       ;; Delete other mail buffers and stuff.
2373       (message-do-send-housekeeping)
2374       (message-do-actions message-send-actions)
2375       ;; Return success.
2376       t)))
2377
2378 (defun message-send-via-mail (arg)
2379   "Send the current message via mail."
2380   (message-send-mail arg))
2381
2382 (defun message-send-via-news (arg)
2383   "Send the current message via news."
2384   (funcall message-send-news-function arg))
2385
2386 (defmacro message-check (type &rest forms)
2387   "Eval FORMS if TYPE is to be checked."
2388   `(or (message-check-element ,type)
2389        (save-excursion
2390          ,@forms)))
2391
2392 (put 'message-check 'lisp-indent-function 1)
2393 (put 'message-check 'edebug-form-spec '(form body))
2394
2395 (defun message-fix-before-sending ()
2396   "Do various things to make the message nice before sending it."
2397   ;; Make sure there's a newline at the end of the message.
2398   (goto-char (point-max))
2399   (unless (bolp)
2400     (insert "\n"))
2401   ;; Delete all invisible text.
2402   (message-check 'invisible-text
2403     (when (text-property-any (point-min) (point-max) 'invisible t)
2404       (put-text-property (point-min) (point-max) 'invisible nil)
2405       (unless (yes-or-no-p
2406                "Invisible text found and made visible; continue posting? ")
2407         (error "Invisible text found and made visible")))))
2408
2409 (defun message-add-action (action &rest types)
2410   "Add ACTION to be performed when doing an exit of type TYPES."
2411   (let (var)
2412     (while types
2413       (set (setq var (intern (format "message-%s-actions" (pop types))))
2414            (nconc (symbol-value var) (list action))))))
2415
2416 (defun message-do-actions (actions)
2417   "Perform all actions in ACTIONS."
2418   ;; Now perform actions on successful sending.
2419   (while actions
2420     (ignore-errors
2421       (cond
2422        ;; A simple function.
2423        ((message-functionp (car actions))
2424         (funcall (car actions)))
2425        ;; Something to be evaled.
2426        (t
2427         (eval (car actions)))))
2428     (pop actions)))
2429
2430 (defun message-send-mail-partially ()
2431   "Send mail as message/partial."
2432   ;; replace the header delimiter with a blank line
2433   (goto-char (point-min))
2434   (re-search-forward
2435    (concat "^" (regexp-quote mail-header-separator) "\n"))
2436   (replace-match "\n")
2437   (run-hooks 'message-send-mail-hook)
2438   (let ((p (goto-char (point-min)))
2439         (tembuf (message-generate-new-buffer-clone-locals " message temp"))
2440         (curbuf (current-buffer))
2441         (id (message-make-message-id)) (n 1)
2442         plist total  header required-mail-headers)
2443     (while (not (eobp))
2444       (if (< (point-max) (+ p message-send-mail-partially-limit))
2445           (goto-char (point-max))
2446         (goto-char (+ p message-send-mail-partially-limit))
2447         (beginning-of-line)
2448         (if (<= (point) p) (forward-line 1))) ;; In case of bad message.
2449       (push p plist)
2450       (setq p (point)))
2451     (setq total (length plist))
2452     (push (point-max) plist)
2453     (setq plist (nreverse plist))
2454     (unwind-protect
2455         (save-excursion
2456           (setq p (pop plist))
2457           (while plist
2458             (set-buffer curbuf)
2459             (copy-to-buffer tembuf p (car plist))
2460             (set-buffer tembuf)
2461             (goto-char (point-min))
2462             (if header
2463                 (progn
2464                   (goto-char (point-min))
2465                   (narrow-to-region (point) (point))
2466                   (insert header))
2467               (message-goto-eoh)
2468               (setq header (buffer-substring (point-min) (point)))
2469               (goto-char (point-min))
2470               (narrow-to-region (point) (point))
2471               (insert header)
2472               (message-remove-header "Mime-Version")
2473               (message-remove-header "Content-Type")
2474               (message-remove-header "Content-Transfer-Encoding")
2475               (message-remove-header "Message-ID")
2476               (message-remove-header "Lines")
2477               (goto-char (point-max))
2478               (insert "Mime-Version: 1.0\n")
2479               (setq header (buffer-substring (point-min) (point-max))))
2480             (goto-char (point-max))
2481             (insert (format "Content-Type: message/partial; id=\"%s\"; number=%d; total=%d\n\n"
2482                             id n total))
2483             (forward-char -1)
2484             (let ((mail-header-separator ""))
2485               (when (memq 'Message-ID message-required-mail-headers)
2486                 (insert "Message-ID: " (message-make-message-id) "\n"))
2487               (when (memq 'Lines message-required-mail-headers)
2488                 (insert "Lines: " (message-make-lines) "\n"))
2489               (message-goto-subject)
2490               (end-of-line)
2491               (insert (format " (%d/%d)" n total))
2492               (widen)
2493               (mm-with-unibyte-current-buffer
2494                 (funcall (or message-send-mail-real-function
2495                              message-send-mail-function))))
2496             (setq n (+ n 1))
2497             (setq p (pop plist))
2498             (erase-buffer)))
2499       (kill-buffer tembuf))))
2500
2501 (defun message-send-mail (&optional arg)
2502   (require 'mail-utils)
2503   (let* ((tembuf (message-generate-new-buffer-clone-locals " message temp"))
2504          (case-fold-search nil)
2505          (news (message-news-p))
2506          (mailbuf (current-buffer))
2507          (message-this-is-mail t)
2508          (message-posting-charset
2509           (if (fboundp 'gnus-setup-posting-charset)
2510               (gnus-setup-posting-charset nil)
2511             message-posting-charset)))
2512     (save-restriction
2513       (message-narrow-to-headers)
2514       ;; Insert some headers.
2515       (let ((message-deletable-headers
2516              (if news nil message-deletable-headers)))
2517         (message-generate-headers message-required-mail-headers))
2518       ;; Let the user do all of the above.
2519       (run-hooks 'message-header-hook))
2520     (unwind-protect
2521         (save-excursion
2522           (set-buffer tembuf)
2523           (erase-buffer)
2524           ;; Avoid copying text props.
2525           (insert (with-current-buffer mailbuf
2526                     (buffer-substring-no-properties (point-min) (point-max))))
2527           ;; Remove some headers.
2528           (message-encode-message-body)
2529           (save-restriction
2530             (message-narrow-to-headers)
2531             ;; We (re)generate the Lines header.
2532             (when (memq 'Lines message-required-mail-headers)
2533               (message-generate-headers '(Lines)))
2534             ;; Remove some headers.
2535             (message-remove-header message-ignored-mail-headers t)
2536             (let ((mail-parse-charset message-default-charset))
2537               (mail-encode-encoded-word-buffer)))
2538           (goto-char (point-max))
2539           ;; require one newline at the end.
2540           (or (= (preceding-char) ?\n)
2541               (insert ?\n))
2542           (when
2543               (save-restriction
2544                 (message-narrow-to-headers)
2545                 (and news
2546                      (or (message-fetch-field "cc")
2547                          (message-fetch-field "to"))
2548                      (let ((content-type (message-fetch-field "content-type")))
2549                        (or
2550                         (not content-type)
2551                         (string= "text/plain"
2552                                  (car
2553                                   (mail-header-parse-content-type
2554                                    content-type)))))))
2555             (message-insert-courtesy-copy))
2556           (if (or (not message-send-mail-partially-limit)
2557                   (< (point-max) message-send-mail-partially-limit)
2558                   (not (y-or-n-p "Message exceeds message-send-mail-partially-limit, send in parts? ")))
2559               (mm-with-unibyte-current-buffer
2560                 (message "Sending via mail...")
2561                 (funcall (or message-send-mail-real-function
2562                              message-send-mail-function)))
2563             (message-send-mail-partially)))
2564       (kill-buffer tembuf))
2565     (set-buffer mailbuf)
2566     (push 'mail message-sent-message-via)))
2567
2568 (defun message-send-mail-with-sendmail ()
2569   "Send off the prepared buffer with sendmail."
2570   (let ((errbuf (if message-interactive
2571                     (message-generate-new-buffer-clone-locals
2572                      " sendmail errors")
2573                   0))
2574         resend-to-addresses delimline)
2575     (let ((case-fold-search t))
2576       (save-restriction
2577         (message-narrow-to-headers)
2578         (setq resend-to-addresses (message-fetch-field "resent-to")))
2579       ;; Change header-delimiter to be what sendmail expects.
2580       (goto-char (point-min))
2581       (re-search-forward
2582        (concat "^" (regexp-quote mail-header-separator) "\n"))
2583       (replace-match "\n")
2584       (backward-char 1)
2585       (setq delimline (point-marker))
2586       (run-hooks 'message-send-mail-hook)
2587       ;; Insert an extra newline if we need it to work around
2588       ;; Sun's bug that swallows newlines.
2589       (goto-char (1+ delimline))
2590       (when (eval message-mailer-swallows-blank-line)
2591         (newline))
2592       (when message-interactive
2593         (save-excursion
2594           (set-buffer errbuf)
2595           (erase-buffer))))
2596     (let ((default-directory "/")
2597           (coding-system-for-write message-send-coding-system))
2598       (apply 'call-process-region
2599              (append (list (point-min) (point-max)
2600                            (if (boundp 'sendmail-program)
2601                                sendmail-program
2602                              "/usr/lib/sendmail")
2603                            nil errbuf nil "-oi")
2604                      ;; Always specify who from,
2605                      ;; since some systems have broken sendmails.
2606                      ;; But some systems are more broken with -f, so
2607                      ;; we'll let users override this.
2608                      (if (null message-sendmail-f-is-evil)
2609                          (list "-f" (message-make-address)))
2610                      ;; These mean "report errors by mail"
2611                      ;; and "deliver in background".
2612                      (if (null message-interactive) '("-oem" "-odb"))
2613                      ;; Get the addresses from the message
2614                      ;; unless this is a resend.
2615                      ;; We must not do that for a resend
2616                      ;; because we would find the original addresses.
2617                      ;; For a resend, include the specific addresses.
2618                      (if resend-to-addresses
2619                          (list resend-to-addresses)
2620                        '("-t")))))
2621     (when message-interactive
2622       (save-excursion
2623         (set-buffer errbuf)
2624         (goto-char (point-min))
2625         (while (re-search-forward "\n\n* *" nil t)
2626           (replace-match "; "))
2627         (if (not (zerop (buffer-size)))
2628             (error "Sending...failed to %s"
2629                    (buffer-substring (point-min) (point-max)))))
2630       (when (bufferp errbuf)
2631         (kill-buffer errbuf)))))
2632
2633 (defun message-send-mail-with-qmail ()
2634   "Pass the prepared message buffer to qmail-inject.
2635 Refer to the documentation for the variable `message-send-mail-function'
2636 to find out how to use this."
2637   ;; replace the header delimiter with a blank line
2638   (goto-char (point-min))
2639   (re-search-forward
2640    (concat "^" (regexp-quote mail-header-separator) "\n"))
2641   (replace-match "\n")
2642   (run-hooks 'message-send-mail-hook)
2643   ;; send the message
2644   (case
2645       (let ((coding-system-for-write message-send-coding-system))
2646         (apply
2647          'call-process-region 1 (point-max) message-qmail-inject-program
2648          nil nil nil
2649          ;; qmail-inject's default behaviour is to look for addresses on the
2650          ;; command line; if there're none, it scans the headers.
2651          ;; yes, it does The Right Thing w.r.t. Resent-To and it's kin.
2652          ;;
2653          ;; in general, ALL of qmail-inject's defaults are perfect for simply
2654          ;; reading a formatted (i. e., at least a To: or Resent-To header)
2655          ;; message from stdin.
2656          ;;
2657          ;; qmail also has the advantage of not having been raped by
2658          ;; various vendors, so we don't have to allow for that, either --
2659          ;; compare this with message-send-mail-with-sendmail and weep
2660          ;; for sendmail's lost innocence.
2661          ;;
2662          ;; all this is way cool coz it lets us keep the arguments entirely
2663          ;; free for -inject-arguments -- a big win for the user and for us
2664          ;; since we don't have to play that double-guessing game and the user
2665          ;; gets full control (no gestapo'ish -f's, for instance).  --sj
2666          message-qmail-inject-args))
2667     ;; qmail-inject doesn't say anything on it's stdout/stderr,
2668     ;; we have to look at the retval instead
2669     (0 nil)
2670     (100 (error "qmail-inject reported permanent failure"))
2671     (111 (error "qmail-inject reported transient failure"))
2672     ;; should never happen
2673     (t   (error "qmail-inject reported unknown failure"))))
2674
2675 (defun message-send-mail-with-mh ()
2676   "Send the prepared message buffer with mh."
2677   (let ((mh-previous-window-config nil)
2678         (name (mh-new-draft-name)))
2679     (setq buffer-file-name name)
2680     ;; MH wants to generate these headers itself.
2681     (when message-mh-deletable-headers
2682       (let ((headers message-mh-deletable-headers))
2683         (while headers
2684           (goto-char (point-min))
2685           (and (re-search-forward
2686                 (concat "^" (symbol-name (car headers)) ": *") nil t)
2687                (message-delete-line))
2688           (pop headers))))
2689     (run-hooks 'message-send-mail-hook)
2690     ;; Pass it on to mh.
2691     (mh-send-letter)))
2692
2693 (defun message-send-news (&optional arg)
2694   (let* ((tembuf (message-generate-new-buffer-clone-locals " *message temp*"))
2695          (case-fold-search nil)
2696          (method (if (message-functionp message-post-method)
2697                      (funcall message-post-method arg)
2698                    message-post-method))
2699          (newsgroups-field (save-restriction
2700                             (message-narrow-to-headers-or-head)
2701                             (message-fetch-field "Newsgroups")))
2702          (followup-field (save-restriction
2703                            (message-narrow-to-headers-or-head)
2704                            (message-fetch-field "Followup-To")))
2705          ;; BUG: We really need to get the charset for each name in the
2706          ;; Newsgroups and Followup-To lines to allow crossposting
2707          ;; between group namess with incompatible character sets.
2708          ;; -- Per Abrahamsen <abraham@dina.kvl.dk> 2001-10-08.
2709          (group-field-charset
2710           (gnus-group-name-charset method newsgroups-field))
2711          (followup-field-charset 
2712           (gnus-group-name-charset method (or followup-field "")))
2713          (rfc2047-header-encoding-alist
2714           (append (when group-field-charset
2715                     (list (cons "Newsgroups" group-field-charset)))
2716                   (when followup-field-charset
2717                     (list (cons "Followup-To" followup-field-charset)))
2718                   rfc2047-header-encoding-alist))
2719          (messbuf (current-buffer))
2720          (message-syntax-checks
2721           (if (and arg
2722                    (listp message-syntax-checks))
2723               (cons '(existing-newsgroups . disabled)
2724                     message-syntax-checks)
2725             message-syntax-checks))
2726          (message-this-is-news t)
2727          (message-posting-charset
2728           (gnus-setup-posting-charset newsgroups-field))
2729          result)
2730     (if (not (message-check-news-body-syntax))
2731         nil
2732       (save-restriction
2733         (message-narrow-to-headers)
2734         ;; Insert some headers.
2735         (message-generate-headers message-required-news-headers)
2736         ;; Let the user do all of the above.
2737         (run-hooks 'message-header-hook))
2738       ;; Note: This check will be disabled by the ".*" default value for
2739       ;; gnus-group-name-charset-group-alist. -- Pa 2001-10-07.
2740       (when (and group-field-charset
2741                  (listp message-syntax-checks))
2742         (setq message-syntax-checks
2743               (cons '(valid-newsgroups . disabled)
2744                     message-syntax-checks)))
2745       (message-cleanup-headers)
2746       (if (not (let ((message-post-method method))
2747                  (message-check-news-syntax)))
2748           nil
2749         (unwind-protect
2750             (save-excursion
2751               (set-buffer tembuf)
2752               (buffer-disable-undo)
2753               (erase-buffer)
2754               ;; Avoid copying text props.
2755               (insert (with-current-buffer messbuf
2756                         (buffer-substring-no-properties
2757                          (point-min) (point-max))))
2758               (message-encode-message-body)
2759               ;; Remove some headers.
2760               (save-restriction
2761                 (message-narrow-to-headers)
2762                 ;; We (re)generate the Lines header.
2763                 (when (memq 'Lines message-required-mail-headers)
2764                   (message-generate-headers '(Lines)))
2765                 ;; Remove some headers.
2766                 (message-remove-header message-ignored-news-headers t)
2767                 (let ((mail-parse-charset message-default-charset))
2768                   (mail-encode-encoded-word-buffer)))
2769               (goto-char (point-max))
2770               ;; require one newline at the end.
2771               (or (= (preceding-char) ?\n)
2772                   (insert ?\n))
2773               (let ((case-fold-search t))
2774                 ;; Remove the delimiter.
2775                 (goto-char (point-min))
2776                 (re-search-forward
2777                  (concat "^" (regexp-quote mail-header-separator) "\n"))
2778                 (replace-match "\n")
2779                 (backward-char 1))
2780               (run-hooks 'message-send-news-hook)
2781               (gnus-open-server method)
2782               (message "Sending news with %s..." (gnus-server-string method))
2783               (setq result (let ((mail-header-separator ""))
2784                              (gnus-request-post method))))
2785           (kill-buffer tembuf))
2786         (set-buffer messbuf)
2787         (if result
2788             (push 'news message-sent-message-via)
2789           (message "Couldn't send message via news: %s"
2790                    (nnheader-get-report (car method)))
2791           nil)))))
2792
2793 ;;;
2794 ;;; Header generation & syntax checking.
2795 ;;;
2796
2797 (defun message-check-element (type)
2798   "Return non-nil if this TYPE is not to be checked."
2799   (if (eq message-syntax-checks 'dont-check-for-anything-just-trust-me)
2800       t
2801     (let ((able (assq type message-syntax-checks)))
2802       (and (consp able)
2803            (eq (cdr able) 'disabled)))))
2804
2805 (defun message-check-news-syntax ()
2806   "Check the syntax of the message."
2807   (save-excursion
2808     (save-restriction
2809       (widen)
2810       ;; We narrow to the headers and check them first.
2811       (save-excursion
2812         (save-restriction
2813           (message-narrow-to-headers)
2814           (message-check-news-header-syntax))))))
2815
2816 (defun message-check-news-header-syntax ()
2817   (and
2818    ;; Check Newsgroups header.
2819    (message-check 'newsgroups
2820      (let ((group (message-fetch-field "newsgroups")))
2821        (or
2822         (and group
2823              (not (string-match "\\`[ \t]*\\'" group)))
2824         (ignore
2825          (message
2826           "The newsgroups field is empty or missing.  Posting is denied.")))))
2827    ;; Check the Subject header.
2828    (message-check 'subject
2829      (let* ((case-fold-search t)
2830             (subject (message-fetch-field "subject")))
2831        (or
2832         (and subject
2833              (not (string-match "\\`[ \t]*\\'" subject)))
2834         (ignore
2835          (message
2836           "The subject field is empty or missing.  Posting is denied.")))))
2837    ;; Check for commands in Subject.
2838    (message-check 'subject-cmsg
2839      (if (string-match "^cmsg " (message-fetch-field "subject"))
2840          (y-or-n-p
2841           "The control code \"cmsg\" is in the subject.  Really post? ")
2842        t))
2843    ;; Check for multiple identical headers.
2844    (message-check 'multiple-headers
2845      (let (found)
2846        (while (and (not found)
2847                    (re-search-forward "^[^ \t:]+: " nil t))
2848          (save-excursion
2849            (or (re-search-forward
2850                 (concat "^"
2851                         (regexp-quote
2852                          (setq found
2853                                (buffer-substring
2854                                 (match-beginning 0) (- (match-end 0) 2))))
2855                         ":")
2856                 nil t)
2857                (setq found nil))))
2858        (if found
2859            (y-or-n-p (format "Multiple %s headers.  Really post? " found))
2860          t)))
2861    ;; Check for Version and Sendsys.
2862    (message-check 'sendsys
2863      (if (re-search-forward "^Sendsys:\\|^Version:" nil t)
2864          (y-or-n-p
2865           (format "The article contains a %s command.  Really post? "
2866                   (buffer-substring (match-beginning 0)
2867                                     (1- (match-end 0)))))
2868        t))
2869    ;; See whether we can shorten Followup-To.
2870    (message-check 'shorten-followup-to
2871      (let ((newsgroups (message-fetch-field "newsgroups"))
2872            (followup-to (message-fetch-field "followup-to"))
2873            to)
2874        (when (and newsgroups
2875                   (string-match "," newsgroups)
2876                   (not followup-to)
2877                   (not
2878                    (zerop
2879                     (length
2880                      (setq to (completing-read
2881                                "Followups to: (default all groups) "
2882                                (mapcar (lambda (g) (list g))
2883                                        (cons "poster"
2884                                              (message-tokenize-header
2885                                               newsgroups)))))))))
2886          (goto-char (point-min))
2887          (insert "Followup-To: " to "\n"))
2888        t))
2889    ;; Check "Shoot me".
2890    (message-check 'shoot
2891      (if (re-search-forward
2892           "Message-ID.*.i-did-not-set--mail-host-address--so-shoot-me" nil t)
2893          (y-or-n-p "You appear to have a misconfigured system.  Really post? ")
2894        t))
2895    ;; Check for Approved.
2896    (message-check 'approved
2897      (if (re-search-forward "^Approved:" nil t)
2898          (y-or-n-p "The article contains an Approved header.  Really post? ")
2899        t))
2900    ;; Check the Message-ID header.
2901    (message-check 'message-id
2902      (let* ((case-fold-search t)
2903             (message-id (message-fetch-field "message-id" t)))
2904        (or (not message-id)
2905            ;; Is there an @ in the ID?
2906            (and (string-match "@" message-id)
2907                 ;; Is there a dot in the ID?
2908                 (string-match "@[^.]*\\." message-id)
2909                 ;; Does the ID end with a dot?
2910                 (not (string-match "\\.>" message-id)))
2911            (y-or-n-p
2912             (format "The Message-ID looks strange: \"%s\".  Really post? "
2913                     message-id)))))
2914    ;; Check the Newsgroups & Followup-To headers.
2915    (message-check 'existing-newsgroups
2916      (let* ((case-fold-search t)
2917             (newsgroups (message-fetch-field "newsgroups"))
2918             (followup-to (message-fetch-field "followup-to"))
2919             (groups (message-tokenize-header
2920                      (if followup-to
2921                          (concat newsgroups "," followup-to)
2922                        newsgroups)))
2923             (post-method (if (message-functionp message-post-method)
2924                              (funcall message-post-method)
2925                            message-post-method))
2926             ;; KLUDGE to handle nnvirtual groups.  Doing this right
2927             ;; would probably involve a new nnoo function.
2928             ;; -- Per Abrahamsen <abraham@dina.kvl.dk>, 2001-10-17.
2929             (method (if (and (consp post-method) 
2930                              (eq (car post-method) 'nnvirtual)
2931                              gnus-message-group-art)
2932                         (let ((group (car (nnvirtual-find-group-art
2933                                            (car gnus-message-group-art)
2934                                            (cdr gnus-message-group-art)))))
2935                           (gnus-find-method-for-group group))
2936                       post-method))
2937             (known-groups
2938              (mapcar (lambda (n)
2939                        (gnus-group-name-decode 
2940                         (gnus-group-real-name n)
2941                         (gnus-group-name-charset method n)))
2942                      (gnus-groups-from-server method)))
2943             errors)
2944        (while groups
2945          (unless (or (equal (car groups) "poster")
2946                      (member (car groups) known-groups))
2947            (push (car groups) errors))
2948          (pop groups))
2949        (cond
2950         ;; Gnus is not running.
2951         ((or (not (and (boundp 'gnus-active-hashtb)
2952                        gnus-active-hashtb))
2953              (not (boundp 'gnus-read-active-file)))
2954          t)
2955         ;; We don't have all the group names.
2956         ((and (or (not gnus-read-active-file)
2957                   (eq gnus-read-active-file 'some))
2958               errors)
2959          (y-or-n-p
2960           (format
2961            "Really post to %s possibly unknown group%s: %s? "
2962            (if (= (length errors) 1) "this" "these")
2963            (if (= (length errors) 1) "" "s")
2964            (mapconcat 'identity errors ", "))))
2965         ;; There were no errors.
2966         ((not errors)
2967          t)
2968         ;; There are unknown groups.
2969         (t
2970          (y-or-n-p
2971           (format
2972            "Really post to %s unknown group%s: %s? "
2973            (if (= (length errors) 1) "this" "these")
2974            (if (= (length errors) 1) "" "s")
2975            (mapconcat 'identity errors ", ")))))))
2976    ;; Check the Newsgroups & Followup-To headers for syntax errors.
2977    (message-check 'valid-newsgroups
2978      (let ((case-fold-search t)
2979            (headers '("Newsgroups" "Followup-To"))
2980            header error)
2981        (while (and headers (not error))
2982          (when (setq header (mail-fetch-field (car headers)))
2983            (if (or
2984                 (not
2985                  (string-match
2986                   "\\`\\([-+_&.a-zA-Z0-9]+\\)?\\(,[-+_&.a-zA-Z0-9]+\\)*\\'"
2987                   header))
2988                 (memq
2989                  nil (mapcar
2990                       (lambda (g)
2991                         (not (string-match "\\.\\'\\|\\.\\." g)))
2992                       (message-tokenize-header header ","))))
2993                (setq error t)))
2994          (unless error
2995            (pop headers)))
2996        (if (not error)
2997            t
2998          (y-or-n-p
2999           (format "The %s header looks odd: \"%s\".  Really post? "
3000                   (car headers) header)))))
3001    (message-check 'repeated-newsgroups
3002      (let ((case-fold-search t)
3003            (headers '("Newsgroups" "Followup-To"))
3004            header error groups group)
3005        (while (and headers
3006                    (not error))
3007          (when (setq header (mail-fetch-field (pop headers)))
3008            (setq groups (message-tokenize-header header ","))
3009            (while (setq group (pop groups))
3010              (when (member group groups)
3011                (setq error group
3012                      groups nil)))))
3013        (if (not error)
3014            t
3015          (y-or-n-p
3016           (format "Group %s is repeated in headers.  Really post? " error)))))
3017    ;; Check the From header.
3018    (message-check 'from
3019      (let* ((case-fold-search t)
3020             (from (message-fetch-field "from"))
3021             ad)
3022        (cond
3023         ((not from)
3024          (message "There is no From line.  Posting is denied.")
3025          nil)
3026         ((or (not (string-match
3027                    "@[^\\.]*\\."
3028                    (setq ad (nth 1 (mail-extract-address-components
3029                                     from))))) ;larsi@ifi
3030              (string-match "\\.\\." ad) ;larsi@ifi..uio
3031              (string-match "@\\." ad)   ;larsi@.ifi.uio
3032              (string-match "\\.$" ad)   ;larsi@ifi.uio.
3033              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
3034              (string-match "(.*).*(.*)" from)) ;(lars) (lars)
3035          (message
3036           "Denied posting -- the From looks strange: \"%s\"." from)
3037          nil)
3038         ((let ((addresses (rfc822-addresses from)))
3039            (while (and addresses
3040                        (not (eq (string-to-char (car addresses)) ?\()))
3041              (setq addresses (cdr addresses)))
3042            addresses)
3043          (message
3044           "Denied posting -- bad From address: \"%s\"." from)
3045          nil)
3046         (t t))))
3047    ;; Check the Reply-To header.
3048    (message-check 'reply-to
3049      (let* ((case-fold-search t)
3050             (reply-to (message-fetch-field "reply-to"))
3051             ad)
3052        (cond
3053         ((not reply-to)
3054          t)
3055         ((string-match "," reply-to)
3056          (y-or-n-p
3057           (format "Multiple Reply-To addresses: \"%s\". Really post? "
3058                   reply-to)))
3059         ((or (not (string-match
3060                    "@[^\\.]*\\."
3061                    (setq ad (nth 1 (mail-extract-address-components
3062                                     reply-to))))) ;larsi@ifi
3063              (string-match "\\.\\." ad) ;larsi@ifi..uio
3064              (string-match "@\\." ad)   ;larsi@.ifi.uio
3065              (string-match "\\.$" ad)   ;larsi@ifi.uio.
3066              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
3067              (string-match "(.*).*(.*)" reply-to)) ;(lars) (lars)
3068          (y-or-n-p
3069           (format
3070            "The Reply-To looks strange: \"%s\". Really post? "
3071            reply-to)))
3072         (t t))))))
3073
3074 (defun message-check-news-body-syntax ()
3075   (and
3076    ;; Check for long lines.
3077    (message-check 'long-lines
3078      (goto-char (point-min))
3079      (re-search-forward
3080       (concat "^" (regexp-quote mail-header-separator) "$"))
3081      (forward-line 1)
3082      (while (and
3083              (or (looking-at
3084                   "<#\\(/\\)?\\(multipart\\|part\\|external\\|mml\\)")
3085                  (let ((p (point)))
3086                    (end-of-line)
3087                    (< (- (point) p) 80)))
3088              (zerop (forward-line 1))))
3089      (or (bolp)
3090          (eobp)
3091          (y-or-n-p
3092           "You have lines longer than 79 characters.  Really post? ")))
3093    ;; Check whether the article is empty.
3094    (message-check 'empty
3095      (goto-char (point-min))
3096      (re-search-forward
3097       (concat "^" (regexp-quote mail-header-separator) "$"))
3098      (forward-line 1)
3099      (let ((b (point)))
3100        (goto-char (point-max))
3101        (re-search-backward message-signature-separator nil t)
3102        (beginning-of-line)
3103        (or (re-search-backward "[^ \n\t]" b t)
3104            (if (message-gnksa-enable-p 'empty-article)
3105                (y-or-n-p "Empty article.  Really post? ")
3106              (message "Denied posting -- Empty article.")
3107              nil))))
3108    ;; Check for control characters.
3109    (message-check 'control-chars
3110      (if (re-search-forward "[\000-\007\013\015-\032\034-\037\200-\237]" nil t)
3111          (y-or-n-p
3112           "The article contains control characters.  Really post? ")
3113        t))
3114    ;; Check excessive size.
3115    (message-check 'size
3116      (if (> (buffer-size) 60000)
3117          (y-or-n-p
3118           (format "The article is %d octets long.  Really post? "
3119                   (buffer-size)))
3120        t))
3121    ;; Check whether any new text has been added.
3122    (message-check 'new-text
3123      (or
3124       (not message-checksum)
3125       (not (eq (message-checksum) message-checksum))
3126       (if (message-gnksa-enable-p 'quoted-text-only)
3127           (y-or-n-p
3128            "It looks like no new text has been added.  Really post? ")
3129         (message "Denied posting -- no new text has been added.")
3130         nil)))
3131    ;; Check the length of the signature.
3132    (message-check 'signature
3133      (goto-char (point-max))
3134      (if (> (count-lines (point) (point-max)) 5)
3135          (y-or-n-p
3136           (format
3137            "Your .sig is %d lines; it should be max 4.  Really post? "
3138            (1- (count-lines (point) (point-max)))))
3139        t))
3140    ;; Ensure that text follows last quoted portion.
3141    (message-check 'quoting-style
3142      (goto-char (point-max))
3143      (let ((no-problem t))
3144        (when (search-backward-regexp "^>[^\n]*\n" nil t)
3145          (setq no-problem (search-forward-regexp "^[ \t]*[^>\n]" nil t)))
3146        (if no-problem
3147            t
3148          (if (message-gnksa-enable-p 'quoted-text-only)
3149              (y-or-n-p "Your text should follow quoted text.  Really post? ")
3150            ;; Ensure that
3151            (goto-char (point-min))
3152            (re-search-forward
3153             (concat "^" (regexp-quote mail-header-separator) "$"))
3154            (if (search-forward-regexp "^[ \t]*[^>\n]" nil t)
3155                (y-or-n-p "Your text should follow quoted text.  Really post? ")
3156              (message "Denied posting -- only quoted text.")
3157              nil)))))))
3158
3159 (defun message-checksum ()
3160   "Return a \"checksum\" for the current buffer."
3161   (let ((sum 0))
3162     (save-excursion
3163       (goto-char (point-min))
3164       (re-search-forward
3165        (concat "^" (regexp-quote mail-header-separator) "$"))
3166       (while (not (eobp))
3167         (when (not (looking-at "[ \t\n]"))
3168           (setq sum (logxor (ash sum 1) (if (natnump sum) 0 1)
3169                             (char-after))))
3170         (forward-char 1)))
3171     sum))
3172
3173 (defun message-do-fcc ()
3174   "Process Fcc headers in the current buffer."
3175   (let ((case-fold-search t)
3176         (buf (current-buffer))
3177         list file)
3178     (save-excursion
3179       (save-restriction
3180         (message-narrow-to-headers)
3181         (setq file (message-fetch-field "fcc" t)))
3182       (when file
3183         (set-buffer (get-buffer-create " *message temp*"))
3184         (erase-buffer)
3185         (insert-buffer-substring buf)
3186         (message-encode-message-body)
3187         (save-restriction
3188           (message-narrow-to-headers)
3189           (while (setq file (message-fetch-field "fcc" t))
3190             (push file list)
3191             (message-remove-header "fcc" nil t))
3192           (let ((mail-parse-charset message-default-charset)
3193                 (rfc2047-header-encoding-alist
3194                  (cons '("Newsgroups" . default)
3195                        rfc2047-header-encoding-alist)))
3196             (mail-encode-encoded-word-buffer)))
3197         (goto-char (point-min))
3198         (when (re-search-forward
3199                (concat "^" (regexp-quote mail-header-separator) "$")
3200                nil t)
3201           (replace-match "" t t ))
3202         ;; Process FCC operations.
3203         (while list
3204           (setq file (pop list))
3205           (if (string-match "^[ \t]*|[ \t]*\\(.*\\)[ \t]*$" file)
3206               ;; Pipe the article to the program in question.
3207               (call-process-region (point-min) (point-max) shell-file-name
3208                                    nil nil nil shell-command-switch
3209                                    (match-string 1 file))
3210             ;; Save the article.
3211             (setq file (expand-file-name file))
3212             (unless (file-exists-p (file-name-directory file))
3213               (make-directory (file-name-directory file) t))
3214             (if (and message-fcc-handler-function
3215                      (not (eq message-fcc-handler-function 'rmail-output)))
3216                 (funcall message-fcc-handler-function file)
3217               (if (and (file-readable-p file) (mail-file-babyl-p file))
3218                   (rmail-output file 1 nil t)
3219                 (let ((mail-use-rfc822 t))
3220                   (rmail-output file 1 t t))))))
3221         (kill-buffer (current-buffer))))))
3222
3223 (defun message-output (filename)
3224   "Append this article to Unix/babyl mail file FILENAME."
3225   (if (and (file-readable-p filename)
3226            (mail-file-babyl-p filename))
3227       (gnus-output-to-rmail filename t)
3228     (gnus-output-to-mail filename t)))
3229
3230 (defun message-cleanup-headers ()
3231   "Do various automatic cleanups of the headers."
3232   ;; Remove empty lines in the header.
3233   (save-restriction
3234     (message-narrow-to-headers)
3235     ;; Remove blank lines.
3236     (while (re-search-forward "^[ \t]*\n" nil t)
3237       (replace-match "" t t))
3238
3239     ;; Correct Newsgroups and Followup-To headers:  Change sequence of
3240     ;; spaces to comma and eliminate spaces around commas.  Eliminate
3241     ;; embedded line breaks.
3242     (goto-char (point-min))
3243     (while (re-search-forward "^\\(Newsgroups\\|Followup-To\\): +" nil t)
3244       (save-restriction
3245         (narrow-to-region
3246          (point)
3247          (if (re-search-forward "^[^ \t]" nil t)
3248              (match-beginning 0)
3249            (forward-line 1)
3250            (point)))
3251         (goto-char (point-min))
3252         (while (re-search-forward "\n[ \t]+" nil t)
3253           (replace-match " " t t))     ;No line breaks (too confusing)
3254         (goto-char (point-min))
3255         (while (re-search-forward "[ \t\n]*,[ \t\n]*\\|[ \t]+" nil t)
3256           (replace-match "," t t))
3257         (goto-char (point-min))
3258         ;; Remove trailing commas.
3259         (when (re-search-forward ",+$" nil t)
3260           (replace-match "" t t))))))
3261
3262 (defun message-make-date (&optional now)
3263   "Make a valid data header.
3264 If NOW, use that time instead."
3265   (let* ((now (or now (current-time)))
3266          (zone (nth 8 (decode-time now)))
3267          (sign "+"))
3268     (when (< zone 0)
3269       (setq sign "-")
3270       (setq zone (- zone)))
3271     (concat
3272      ;; The day name of the %a spec is locale-specific.  Pfff.
3273      (format "%s, " (capitalize (car (rassoc (nth 6 (decode-time now))
3274                                              parse-time-weekdays))))
3275      (format-time-string "%d" now)
3276      ;; The month name of the %b spec is locale-specific.  Pfff.
3277      (format " %s "
3278              (capitalize (car (rassoc (nth 4 (decode-time now))
3279                                       parse-time-months))))
3280      (format-time-string "%Y %H:%M:%S " now)
3281      ;; We do all of this because XEmacs doesn't have the %z spec.
3282      (format "%s%02d%02d" sign (/ zone 3600) (/ (% zone 3600) 60)))))
3283
3284 (defun message-make-message-id ()
3285   "Make a unique Message-ID."
3286   (concat "<" (message-unique-id)
3287           (let ((psubject (save-excursion (message-fetch-field "subject")))
3288                 (psupersedes
3289                  (save-excursion (message-fetch-field "supersedes"))))
3290             (if (or
3291                  (and message-reply-headers
3292                       (mail-header-references message-reply-headers)
3293                       (mail-header-subject message-reply-headers)
3294                       psubject
3295                       (not (string=
3296                             (message-strip-subject-re
3297                              (mail-header-subject message-reply-headers))
3298                             (message-strip-subject-re psubject))))
3299                  (and psupersedes
3300                       (string-match "_-_@" psupersedes)))
3301                 "_-_" ""))
3302           "@" (message-make-fqdn) ">"))
3303
3304 (defvar message-unique-id-char nil)
3305
3306 ;; If you ever change this function, make sure the new version
3307 ;; cannot generate IDs that the old version could.
3308 ;; You might for example insert a "." somewhere (not next to another dot
3309 ;; or string boundary), or modify the "fsf" string.
3310 (defun message-unique-id ()
3311   ;; Don't use microseconds from (current-time), they may be unsupported.
3312   ;; Instead we use this randomly inited counter.
3313   (setq message-unique-id-char
3314         (% (1+ (or message-unique-id-char (logand (random t) (1- (lsh 1 20)))))
3315            ;; (current-time) returns 16-bit ints,
3316            ;; and 2^16*25 just fits into 4 digits i base 36.
3317            (* 25 25)))
3318   (let ((tm (current-time)))
3319     (concat
3320      (if (memq system-type '(ms-dos emx vax-vms))
3321          (let ((user (downcase (user-login-name))))
3322            (while (string-match "[^a-z0-9_]" user)
3323              (aset user (match-beginning 0) ?_))
3324            user)
3325        (message-number-base36 (user-uid) -1))
3326      (message-number-base36 (+ (car   tm)
3327                                (lsh (% message-unique-id-char 25) 16)) 4)
3328      (message-number-base36 (+ (nth 1 tm)
3329                                (lsh (/ message-unique-id-char 25) 16)) 4)
3330      ;; Append the newsreader name, because while the generated
3331      ;; ID is unique to this newsreader, other newsreaders might
3332      ;; otherwise generate the same ID via another algorithm.
3333      ".fsf")))
3334
3335 (defun message-number-base36 (num len)
3336   (if (if (< len 0)
3337           (<= num 0)
3338         (= len 0))
3339       ""
3340     (concat (message-number-base36 (/ num 36) (1- len))
3341             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
3342                                   (% num 36))))))
3343
3344 (defun message-make-organization ()
3345   "Make an Organization header."
3346   (let* ((organization
3347           (when message-user-organization
3348             (if (message-functionp message-user-organization)
3349                 (funcall message-user-organization)
3350               message-user-organization))))
3351     (save-excursion
3352       (message-set-work-buffer)
3353       (cond ((stringp organization)
3354              (insert organization))
3355             ((and (eq t organization)
3356                   message-user-organization-file
3357                   (file-exists-p message-user-organization-file))
3358              (insert-file-contents message-user-organization-file)))
3359       (goto-char (point-min))
3360       (while (re-search-forward "[\t\n]+" nil t)
3361         (replace-match "" t t))
3362       (unless (zerop (buffer-size))
3363         (buffer-string)))))
3364
3365 (defun message-make-lines ()
3366   "Count the number of lines and return numeric string."
3367   (save-excursion
3368     (save-restriction
3369       (widen)
3370       (message-goto-body)
3371       (int-to-string (count-lines (point) (point-max))))))
3372
3373 (defun message-make-in-reply-to ()
3374   "Return the In-Reply-To header for this message."
3375   (when message-reply-headers
3376     (let ((from (mail-header-from message-reply-headers))
3377           (date (mail-header-date message-reply-headers))
3378           (msg-id (mail-header-message-id message-reply-headers)))
3379       (when from
3380         (let ((stop-pos
3381                (string-match "  *at \\|  *@ \\| *(\\| *<" from)))
3382           (concat msg-id (if msg-id " (")
3383                   (if (and stop-pos
3384                            (not (zerop stop-pos)))
3385                       (substring from 0 stop-pos) from)
3386                   "'s message of \""
3387                   (if (or (not date) (string= date ""))
3388                       "(unknown date)" date)
3389                   "\"" (if msg-id ")")))))))
3390
3391 (defun message-make-distribution ()
3392   "Make a Distribution header."
3393   (let ((orig-distribution (message-fetch-reply-field "distribution")))
3394     (cond ((message-functionp message-distribution-function)
3395            (funcall message-distribution-function))
3396           (t orig-distribution))))
3397
3398 (defun message-make-expires ()
3399   "Return an Expires header based on `message-expires'."
3400   (let ((current (current-time))
3401         (future (* 1.0 message-expires 60 60 24)))
3402     ;; Add the future to current.
3403     (setcar current (+ (car current) (round (/ future (expt 2 16)))))
3404     (setcar (cdr current) (+ (nth 1 current) (% (round future) (expt 2 16))))
3405     (message-make-date current)))
3406
3407 (defun message-make-path ()
3408   "Return uucp path."
3409   (let ((login-name (user-login-name)))
3410     (cond ((null message-user-path)
3411            (concat (system-name) "!" login-name))
3412           ((stringp message-user-path)
3413            ;; Support GENERICPATH.  Suggested by vixie@decwrl.dec.com.
3414            (concat message-user-path "!" login-name))
3415           (t login-name))))
3416
3417 (defun message-make-from ()
3418   "Make a From header."
3419   (let* ((style message-from-style)
3420          (login (message-make-address))
3421          (fullname
3422           (or (and (boundp 'user-full-name)
3423                    user-full-name)
3424               (user-full-name))))
3425     (when (string= fullname "&")
3426       (setq fullname (user-login-name)))
3427     (save-excursion
3428       (message-set-work-buffer)
3429       (cond
3430        ((or (null style)
3431             (equal fullname ""))
3432         (insert login))
3433        ((or (eq style 'angles)
3434             (and (not (eq style 'parens))
3435                  ;; Use angles if no quoting is needed, or if parens would
3436                  ;; need quoting too.
3437                  (or (not (string-match "[^- !#-'*+/-9=?A-Z^-~]" fullname))
3438                      (let ((tmp (concat fullname nil)))
3439                        (while (string-match "([^()]*)" tmp)
3440                          (aset tmp (match-beginning 0) ?-)
3441                          (aset tmp (1- (match-end 0)) ?-))
3442                        (string-match "[\\()]" tmp)))))
3443         (insert fullname)
3444         (goto-char (point-min))
3445         ;; Look for a character that cannot appear unquoted
3446         ;; according to RFC 822.
3447         (when (re-search-forward "[^- !#-'*+/-9=?A-Z^-~]" nil 1)
3448           ;; Quote fullname, escaping specials.
3449           (goto-char (point-min))
3450           (insert "\"")
3451           (while (re-search-forward "[\"\\]" nil 1)
3452             (replace-match "\\\\\\&" t))
3453           (insert "\""))
3454         (insert " <" login ">"))
3455        (t                               ; 'parens or default
3456         (insert login " (")
3457         (let ((fullname-start (point)))
3458           (insert fullname)
3459           (goto-char fullname-start)
3460           ;; RFC 822 says \ and nonmatching parentheses
3461           ;; must be escaped in comments.
3462           ;; Escape every instance of ()\ ...
3463           (while (re-search-forward "[()\\]" nil 1)
3464             (replace-match "\\\\\\&" t))
3465           ;; ... then undo escaping of matching parentheses,
3466           ;; including matching nested parentheses.
3467           (goto-char fullname-start)
3468           (while (re-search-forward
3469                   "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
3470                   nil 1)
3471             (replace-match "\\1(\\3)" t)
3472             (goto-char fullname-start)))
3473         (insert ")")))
3474       (buffer-string))))
3475
3476 (defun message-make-sender ()
3477   "Return the \"real\" user address.
3478 This function tries to ignore all user modifications, and
3479 give as trustworthy answer as possible."
3480   (concat (user-login-name) "@" (system-name)))
3481
3482 (defun message-make-address ()
3483   "Make the address of the user."
3484   (or (message-user-mail-address)
3485       (concat (user-login-name) "@" (message-make-domain))))
3486
3487 (defun message-user-mail-address ()
3488   "Return the pertinent part of `user-mail-address'."
3489   (when user-mail-address
3490     (if (string-match " " user-mail-address)
3491         (nth 1 (mail-extract-address-components user-mail-address))
3492       user-mail-address)))
3493
3494 (defun message-make-fqdn ()
3495   "Return user's fully qualified domain name."
3496   (let ((system-name (system-name))
3497         (user-mail (message-user-mail-address)))
3498     (cond
3499      ((and (string-match "[^.]\\.[^.]" system-name)
3500            (not (string-match message-bogus-system-names system-name)))
3501       ;; `system-name' returned the right result.
3502       system-name)
3503      ;; Try `mail-host-address'.
3504      ((and (boundp 'mail-host-address)
3505            (stringp mail-host-address)
3506            (string-match "\\." mail-host-address))
3507       mail-host-address)
3508      ;; We try `user-mail-address' as a backup.
3509      ((and user-mail
3510            (string-match "\\." user-mail)
3511            (string-match "@\\(.*\\)\\'" user-mail))
3512       (match-string 1 user-mail))
3513      ;; Default to this bogus thing.
3514      (t
3515       (concat system-name ".i-did-not-set--mail-host-address--so-shoot-me")))))
3516
3517 (defun message-make-host-name ()
3518   "Return the name of the host."
3519   (let ((fqdn (message-make-fqdn)))
3520     (string-match "^[^.]+\\." fqdn)
3521     (substring fqdn 0 (1- (match-end 0)))))
3522
3523 (defun message-make-domain ()
3524   "Return the domain name."
3525   (or mail-host-address
3526       (message-make-fqdn)))
3527
3528 (defun message-generate-headers (headers)
3529   "Prepare article HEADERS.
3530 Headers already prepared in the buffer are not modified."
3531   (save-restriction
3532     (message-narrow-to-headers)
3533     (let* ((Date (message-make-date))
3534            (Message-ID (message-make-message-id))
3535            (Organization (message-make-organization))
3536            (From (message-make-from))
3537            (Path (message-make-path))
3538            (Subject nil)
3539            (Newsgroups nil)
3540            (In-Reply-To (message-make-in-reply-to))
3541            (To nil)
3542            (Distribution (message-make-distribution))
3543            (Lines (message-make-lines))
3544            (User-Agent message-newsreader)
3545            (Expires (message-make-expires))
3546            (case-fold-search t)
3547            header value elem)
3548       ;; First we remove any old generated headers.
3549       (let ((headers message-deletable-headers))
3550         (unless (buffer-modified-p)
3551           (setq headers (delq 'Message-ID (copy-sequence headers))))
3552         (while headers
3553           (goto-char (point-min))
3554           (and (re-search-forward
3555                 (concat "^" (symbol-name (car headers)) ": *") nil t)
3556                (get-text-property (1+ (match-beginning 0)) 'message-deletable)
3557                (message-delete-line))
3558           (pop headers)))
3559       ;; Go through all the required headers and see if they are in the
3560       ;; articles already.  If they are not, or are empty, they are
3561       ;; inserted automatically - except for Subject, Newsgroups and
3562       ;; Distribution.
3563       (while headers
3564         (goto-char (point-min))
3565         (setq elem (pop headers))
3566         (if (consp elem)
3567             (if (eq (car elem) 'optional)
3568                 (setq header (cdr elem))
3569               (setq header (car elem)))
3570           (setq header elem))
3571         (when (or (not (re-search-forward
3572                         (concat "^"
3573                                 (regexp-quote
3574                                  (downcase
3575                                   (if (stringp header)
3576                                       header
3577                                     (symbol-name header))))
3578                                 ":")
3579                         nil t))
3580                   (progn
3581                     ;; The header was found.  We insert a space after the
3582                     ;; colon, if there is none.
3583                     (if (/= (char-after) ? ) (insert " ") (forward-char 1))
3584                     ;; Find out whether the header is empty...
3585                     (looking-at "[ \t]*\n[^ \t]")))
3586           ;; So we find out what value we should insert.
3587           (setq value
3588                 (cond
3589                  ((and (consp elem) (eq (car elem) 'optional))
3590                   ;; This is an optional header.  If the cdr of this
3591                   ;; is something that is nil, then we do not insert
3592                   ;; this header.
3593                   (setq header (cdr elem))
3594                   (or (and (fboundp (cdr elem)) (funcall (cdr elem)))
3595                       (and (boundp (cdr elem)) (symbol-value (cdr elem)))))
3596                  ((consp elem)
3597                   ;; The element is a cons.  Either the cdr is a
3598                   ;; string to be inserted verbatim, or it is a
3599                   ;; function, and we insert the value returned from
3600                   ;; this function.
3601                   (or (and (stringp (cdr elem)) (cdr elem))
3602                       (and (fboundp (cdr elem)) (funcall (cdr elem)))))
3603                  ((and (boundp header) (symbol-value header))
3604                   ;; The element is a symbol.  We insert the value
3605                   ;; of this symbol, if any.
3606                   (symbol-value header))
3607                  ((not (message-check-element header))
3608                   ;; We couldn't generate a value for this header,
3609                   ;; so we just ask the user.
3610                   (read-from-minibuffer
3611                    (format "Empty header for %s; enter value: " header)))))
3612           ;; Finally insert the header.
3613           (when (and value
3614                      (not (equal value "")))
3615             (save-excursion
3616               (if (bolp)
3617                   (progn
3618                     ;; This header didn't exist, so we insert it.
3619                     (goto-char (point-max))
3620                     (insert (if (stringp header) header (symbol-name header))
3621                             ": " value "\n")
3622                     (forward-line -1))
3623                 ;; The value of this header was empty, so we clear
3624                 ;; totally and insert the new value.
3625                 (delete-region (point) (gnus-point-at-eol))
3626                 (insert value))
3627               ;; Add the deletable property to the headers that require it.
3628               (and (memq header message-deletable-headers)
3629                    (progn (beginning-of-line) (looking-at "[^:]+: "))
3630                    (add-text-properties
3631                     (point) (match-end 0)
3632                     '(message-deletable t face italic) (current-buffer)))))))
3633       ;; Insert new Sender if the From is strange.
3634       (let ((from (message-fetch-field "from"))
3635             (sender (message-fetch-field "sender"))
3636             (secure-sender (message-make-sender)))
3637         (when (and from
3638                    (not (message-check-element 'sender))
3639                    (not (string=
3640                          (downcase
3641                           (cadr (mail-extract-address-components from)))
3642                          (downcase secure-sender)))
3643                    (or (null sender)
3644                        (not
3645                         (string=
3646                          (downcase
3647                           (cadr (mail-extract-address-components sender)))
3648                          (downcase secure-sender)))))
3649           (goto-char (point-min))
3650           ;; Rename any old Sender headers to Original-Sender.
3651           (when (re-search-forward "^\\(Original-\\)*Sender:" nil t)
3652             (beginning-of-line)
3653             (insert "Original-")
3654             (beginning-of-line))
3655           (when (or (message-news-p)
3656                     (string-match "@.+\\.." secure-sender))
3657             (insert "Sender: " secure-sender "\n")))))))
3658
3659 (defun message-insert-courtesy-copy ()
3660   "Insert a courtesy message in mail copies of combined messages."
3661   (let (newsgroups)
3662     (save-excursion
3663       (save-restriction
3664         (message-narrow-to-headers)
3665         (when (setq newsgroups (message-fetch-field "newsgroups"))
3666           (goto-char (point-max))
3667           (insert "Posted-To: " newsgroups "\n")))
3668       (forward-line 1)
3669       (when message-courtesy-message
3670         (cond
3671          ((string-match "%s" message-courtesy-message)
3672           (insert (format message-courtesy-message newsgroups)))
3673          (t
3674           (insert message-courtesy-message)))))))
3675
3676 ;;;
3677 ;;; Setting up a message buffer
3678 ;;;
3679
3680 (defun message-fill-address (header value)
3681   (save-restriction
3682     (narrow-to-region (point) (point))
3683     (insert (capitalize (symbol-name header))
3684             ": "
3685             (if (consp value) (car value) value)
3686             "\n")
3687     (narrow-to-region (point-min) (1- (point-max)))
3688     (let (quoted last)
3689       (goto-char (point-min))
3690       (while (not (eobp))
3691         (skip-chars-forward "^,\"" (point-max))
3692         (if (or (eq (char-after) ?,)
3693                 (eobp))
3694             (when (not quoted)
3695               (if (and (> (current-column) 78)
3696                        last)
3697                   (progn
3698                     (save-excursion
3699                       (goto-char last)
3700                       (insert "\n\t"))
3701                     (setq last (1+ (point))))
3702                 (setq last (1+ (point)))))
3703           (setq quoted (not quoted)))
3704         (unless (eobp)
3705           (forward-char 1))))
3706     (goto-char (point-max))
3707     (widen)
3708     (forward-line 1)))
3709
3710 (defun message-fill-header (header value)
3711   (let ((begin (point))
3712         (fill-column 78)
3713         (fill-prefix "\t"))
3714     (insert (capitalize (symbol-name header))
3715             ": "
3716             (if (consp value) (car value) value)
3717             "\n")
3718     (save-restriction
3719       (narrow-to-region begin (point))
3720       (fill-region-as-paragraph begin (point))
3721       ;; Tapdance around looong Message-IDs.
3722       (forward-line -1)
3723       (when (looking-at "[ \t]*$")
3724         (message-delete-line))
3725       (goto-char begin)
3726       (re-search-forward ":" nil t)
3727       (when (looking-at "\n[ \t]+")
3728         (replace-match " " t t))
3729       (goto-char (point-max)))))
3730
3731 (defun message-shorten-1 (list cut surplus)
3732   "Cut SURPLUS elements out of LIST, beginning with CUTth one."
3733   (setcdr (nthcdr (- cut 2) list)
3734           (nthcdr (+ (- cut 2) surplus 1) list)))
3735
3736 (defun message-shorten-references (header references)
3737   "Trim REFERENCES to be 21 Message-ID long or less, and fold them.
3738 If folding is disallowed, also check that the REFERENCES are less
3739 than 988 characters long, and if they are not, trim them until they are."
3740   (let ((maxcount 21)
3741         (count 0)
3742         (cut 2)
3743         refs)
3744     (with-temp-buffer
3745       (insert references)
3746       (goto-char (point-min))
3747       ;; Cons a list of valid references.
3748       (while (re-search-forward "<[^>]+>" nil t)
3749         (push (match-string 0) refs))
3750       (setq refs (nreverse refs)
3751             count (length refs)))
3752
3753     ;; If the list has more than MAXCOUNT elements, trim it by
3754     ;; removing the CUTth element and the required number of
3755     ;; elements that follow.
3756     (when (> count maxcount)
3757       (let ((surplus (- count maxcount)))
3758         (message-shorten-1 refs cut surplus)
3759         (decf count surplus)))
3760
3761     ;; If folding is disallowed, make sure the total length (including
3762     ;; the spaces between) will be less than MAXSIZE characters.
3763     ;;
3764     ;; Only disallow folding for News messages. At this point the headers
3765     ;; have not been generated, thus we use message-this-is-news directly.
3766     (when (and message-this-is-news message-cater-to-broken-inn)
3767       (let ((maxsize 988)
3768             (totalsize (+ (apply #'+ (mapcar #'length refs))
3769                           (1- count)))
3770             (surplus 0)
3771             (ptr (nthcdr (1- cut) refs)))
3772         ;; Decide how many elements to cut off...
3773         (while (> totalsize maxsize)
3774           (decf totalsize (1+ (length (car ptr))))
3775           (incf surplus)
3776           (setq ptr (cdr ptr)))
3777         ;; ...and do it.
3778         (when (> surplus 0)
3779           (message-shorten-1 refs cut surplus))))
3780
3781     ;; Finally, collect the references back into a string and insert
3782     ;; it into the buffer.
3783     (let ((refstring (mapconcat #'identity refs " ")))
3784       (if (and message-this-is-news message-cater-to-broken-inn)
3785           (insert (capitalize (symbol-name header)) ": "
3786                   refstring "\n")
3787         (message-fill-header header refstring)))))
3788
3789 (defun message-position-point ()
3790   "Move point to where the user probably wants to find it."
3791   (message-narrow-to-headers)
3792   (cond
3793    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
3794     (search-backward ":" )
3795     (widen)
3796     (forward-char 1)
3797     (if (eq (char-after) ? )
3798         (forward-char 1)
3799       (insert " ")))
3800    (t
3801     (goto-char (point-max))
3802     (widen)
3803     (forward-line 1)
3804     (unless (looking-at "$")
3805       (forward-line 2)))
3806    (sit-for 0)))
3807
3808 (defun message-buffer-name (type &optional to group)
3809   "Return a new (unique) buffer name based on TYPE and TO."
3810   (cond
3811    ;; Generate a new buffer name The Message Way.
3812    ((eq message-generate-new-buffers 'unique)
3813     (generate-new-buffer-name
3814      (concat "*" type
3815              (if to
3816                  (concat " to "
3817                          (or (car (mail-extract-address-components to))
3818                              to) "")
3819                "")
3820              (if (and group (not (string= group ""))) (concat " on " group) "")
3821              "*")))
3822    ;; Check whether `message-generate-new-buffers' is a function,
3823    ;; and if so, call it.
3824    ((message-functionp message-generate-new-buffers)
3825     (funcall message-generate-new-buffers type to group))
3826    ((eq message-generate-new-buffers 'unsent)
3827     (generate-new-buffer-name
3828      (concat "*unsent " type
3829              (if to
3830                  (concat " to "
3831                          (or (car (mail-extract-address-components to))
3832                              to) "")
3833                "")
3834              (if (and group (not (string= group ""))) (concat " on " group) "")
3835              "*")))
3836    ;; Use standard name.
3837    (t
3838     (format "*%s message*" type))))
3839
3840 (defun message-pop-to-buffer (name)
3841   "Pop to buffer NAME, and warn if it already exists and is modified."
3842   (let ((buffer (get-buffer name)))
3843     (if (and buffer
3844              (buffer-name buffer))
3845         (progn
3846           (set-buffer (pop-to-buffer buffer))
3847           (when (and (buffer-modified-p)
3848                      (not (y-or-n-p
3849                            "Message already being composed; erase? ")))
3850             (error "Message being composed")))
3851       (set-buffer (pop-to-buffer name)))
3852     (erase-buffer)
3853     (message-mode)))
3854
3855 (defun message-do-send-housekeeping ()
3856   "Kill old message buffers."
3857   ;; We might have sent this buffer already.  Delete it from the
3858   ;; list of buffers.
3859   (setq message-buffer-list (delq (current-buffer) message-buffer-list))
3860   (while (and message-max-buffers
3861               message-buffer-list
3862               (>= (length message-buffer-list) message-max-buffers))
3863     ;; Kill the oldest buffer -- unless it has been changed.
3864     (let ((buffer (pop message-buffer-list)))
3865       (when (and (buffer-name buffer)
3866                  (not (buffer-modified-p buffer)))
3867         (kill-buffer buffer))))
3868   ;; Rename the buffer.
3869   (if message-send-rename-function
3870       (funcall message-send-rename-function)
3871     ;; Note: mail-abbrevs of XEmacs renames buffer name behind Gnus.
3872     (when (string-match
3873            "\\`\\*\\(sent \\|unsent \\)?\\(.+\\)\\*[^\\*]*\\|\\`mail to "
3874            (buffer-name))
3875       (let ((name (match-string 2 (buffer-name)))
3876             to group)
3877         (if (not (or (null name)
3878                      (string-equal name "mail")
3879                      (string-equal name "news")))
3880             (setq name (concat "*sent " name "*"))
3881           (message-narrow-to-headers)
3882           (setq to (message-fetch-field "to"))
3883           (setq group (message-fetch-field "newsgroups"))
3884           (widen)
3885           (setq name
3886                 (cond
3887                  (to (concat "*sent mail to "
3888                              (or (car (mail-extract-address-components to))
3889                                  to) "*"))
3890                  ((and group (not (string= group "")))
3891                   (concat "*sent news on " group "*"))
3892                  (t "*sent mail*"))))
3893         (unless (string-equal name (buffer-name))
3894           (rename-buffer name t)))))
3895   ;; Push the current buffer onto the list.
3896   (when message-max-buffers
3897     (setq message-buffer-list
3898           (nconc message-buffer-list (list (current-buffer))))))
3899
3900 (defun message-mail-user-agent ()
3901   (let ((mua (cond
3902               ((not message-mail-user-agent) nil)
3903               ((eq message-mail-user-agent t) mail-user-agent)
3904               (t message-mail-user-agent))))
3905     (if (memq mua '(message-user-agent gnus-user-agent))
3906         nil
3907       mua)))
3908
3909 (defun message-setup (headers &optional replybuffer actions switch-function)
3910   (let ((mua (message-mail-user-agent))
3911         subject to field yank-action)
3912     (if (not (and message-this-is-mail mua))
3913         (message-setup-1 headers replybuffer actions)
3914       (if replybuffer
3915           (setq yank-action (list 'insert-buffer replybuffer)))
3916       (setq headers (copy-sequence headers))
3917       (setq field (assq 'Subject headers))
3918       (when field
3919         (setq subject (cdr field))
3920         (setq headers (delq field headers)))
3921       (setq field (assq 'To headers))
3922       (when field
3923         (setq to (cdr field))
3924         (setq headers (delq field headers)))
3925       (let ((mail-user-agent mua))
3926         (compose-mail to subject
3927                       (mapcar (lambda (item)
3928                                 (cons
3929                                  (format "%s" (car item))
3930                                  (cdr item)))
3931                               headers)
3932                       nil switch-function yank-action actions)))))
3933
3934 ;;;(defvar mc-modes-alist)
3935 (defun message-setup-1 (headers &optional replybuffer actions)
3936 ;;;   (when (and (boundp 'mc-modes-alist)
3937 ;;;          (not (assq 'message-mode mc-modes-alist)))
3938 ;;;     (push '(message-mode (encrypt . mc-encrypt-message)
3939 ;;;                      (sign . mc-sign-message))
3940 ;;;       mc-modes-alist))
3941   (when actions
3942     (setq message-send-actions actions))
3943   (setq message-reply-buffer replybuffer)
3944   (goto-char (point-min))
3945   ;; Insert all the headers.
3946   (mail-header-format
3947    (let ((h headers)
3948          (alist message-header-format-alist))
3949      (while h
3950        (unless (assq (caar h) message-header-format-alist)
3951          (push (list (caar h)) alist))
3952        (pop h))
3953      alist)
3954    headers)
3955   (delete-region (point) (progn (forward-line -1) (point)))
3956   (when message-default-headers
3957     (insert message-default-headers)
3958     (or (bolp) (insert ?\n)))
3959   (put-text-property
3960    (point)
3961    (progn
3962      (insert mail-header-separator "\n")
3963      (1- (point)))
3964    'read-only nil)
3965   (forward-line -1)
3966   (when (message-news-p)
3967     (when message-default-news-headers
3968       (insert message-default-news-headers)
3969       (or (bolp) (insert ?\n)))
3970     (when message-generate-headers-first
3971       (message-generate-headers
3972        (delq 'Lines
3973              (delq 'Subject
3974                    (copy-sequence message-required-news-headers))))))
3975   (when (message-mail-p)
3976     (when message-default-mail-headers
3977       (insert message-default-mail-headers)
3978       (or (bolp) (insert ?\n)))
3979     (when message-generate-headers-first
3980       (message-generate-headers
3981        (delq 'Lines
3982              (delq 'Subject
3983                    (copy-sequence message-required-mail-headers))))))
3984   (run-hooks 'message-signature-setup-hook)
3985   (message-insert-signature)
3986   (save-restriction
3987     (message-narrow-to-headers)
3988     (if message-alternative-emails
3989         (message-use-alternative-email-as-from))
3990     (run-hooks 'message-header-setup-hook))
3991   (set-buffer-modified-p nil)
3992   (setq buffer-undo-list nil)
3993   (run-hooks 'message-setup-hook)
3994   (save-restriction
3995     (message-narrow-to-headers)
3996     (put-text-property (point-min) (point-max) 'field 'header))
3997   (message-position-point)
3998   (undo-boundary))
3999
4000 (defun message-set-auto-save-file-name ()
4001   "Associate the message buffer with a file in the drafts directory."
4002   (when message-auto-save-directory
4003     (unless (file-directory-p
4004              (directory-file-name message-auto-save-directory))
4005       (gnus-make-directory message-auto-save-directory))
4006     (if (gnus-alive-p)
4007         (setq message-draft-article
4008               (nndraft-request-associate-buffer "drafts"))
4009       (setq buffer-file-name (expand-file-name
4010                               (if (memq system-type 
4011                                         '(ms-dos ms-windows windows-nt 
4012                                                  cygwin32 win32 w32 
4013                                                  mswindows))
4014                                   "message"
4015                                 "*message*")
4016                               message-auto-save-directory))
4017       (setq buffer-auto-save-file-name (make-auto-save-file-name)))
4018     (clear-visited-file-modtime)
4019     (setq buffer-file-coding-system message-draft-coding-system)))
4020
4021 (defun message-disassociate-draft ()
4022   "Disassociate the message buffer from the drafts directory."
4023   (when message-draft-article
4024     (nndraft-request-expire-articles
4025      (list message-draft-article) "drafts" nil t)))
4026
4027 (defun message-insert-headers ()
4028   "Generate the headers for the article."
4029   (interactive)
4030   (save-excursion
4031     (save-restriction
4032       (message-narrow-to-headers)
4033       (when (message-news-p)
4034         (message-generate-headers
4035          (delq 'Lines
4036                (delq 'Subject
4037                      (copy-sequence message-required-news-headers)))))
4038       (when (message-mail-p)
4039         (message-generate-headers
4040          (delq 'Lines
4041                (delq 'Subject
4042                      (copy-sequence message-required-mail-headers))))))))
4043
4044 \f
4045
4046 ;;;
4047 ;;; Commands for interfacing with message
4048 ;;;
4049
4050 ;;;###autoload
4051 (defun message-mail (&optional to subject
4052                                other-headers continue switch-function
4053                                yank-action send-actions)
4054   "Start editing a mail message to be sent.
4055 OTHER-HEADERS is an alist of header/value pairs."
4056   (interactive)
4057   (let ((message-this-is-mail t) replybuffer)
4058     (unless (message-mail-user-agent)
4059       (message-pop-to-buffer (message-buffer-name "mail" to)))
4060     ;; FIXME: message-mail should do something if YANK-ACTION is not
4061     ;; insert-buffer.
4062     (and (consp yank-action) (eq (car yank-action) 'insert-buffer)
4063          (setq replybuffer (nth 1 yank-action)))
4064     (message-setup
4065      (nconc
4066       `((To . ,(or to "")) (Subject . ,(or subject "")))
4067       (when other-headers other-headers))
4068      replybuffer send-actions)
4069     ;; FIXME: Should return nil if failure.
4070     t))
4071
4072 ;;;###autoload
4073 (defun message-news (&optional newsgroups subject)
4074   "Start editing a news article to be sent."
4075   (interactive)
4076   (let ((message-this-is-news t))
4077     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups))
4078     (message-setup `((Newsgroups . ,(or newsgroups ""))
4079                      (Subject . ,(or subject ""))))))
4080
4081 (defun message-get-reply-headers (wide &optional to-address)
4082   (let (follow-to mct never-mct from to cc reply-to mrt mft ccalist)
4083     ;; Find all relevant headers we need.
4084     (setq from (message-fetch-field "from")
4085           to (message-fetch-field "to")
4086           cc (message-fetch-field "cc")
4087           mct (message-fetch-field "mail-copies-to")
4088           reply-to (message-fetch-field "reply-to")
4089           mrt (message-fetch-field "mail-reply-to")
4090           mft (and message-use-mail-followup-to
4091                    (message-fetch-field "mail-followup-to")))
4092
4093     ;; Handle special values of Mail-Copies-To.
4094     (when mct
4095       (cond ((or (equal (downcase mct) "never")
4096                  (equal (downcase mct) "nobody"))
4097              (setq never-mct t)
4098              (setq mct nil))
4099             ((or (equal (downcase mct) "always")
4100                  (equal (downcase mct) "poster"))
4101              (setq mct (or mrt reply-to from)))))
4102
4103     (if (and (not mft)
4104              (or (not wide)
4105                  to-address))
4106         (progn
4107           (setq follow-to (list (cons 'To (or to-address mrt reply-to from))))
4108           (when (and (and wide mct)
4109                      (not (member (cons 'To mct) follow-to)))
4110             (push (cons 'Cc mct) follow-to)))
4111       (let (ccalist)
4112         (save-excursion
4113           (message-set-work-buffer)
4114           (if (and mft
4115                    wide
4116                    (or (not (eq message-use-mail-followup-to 'ask))
4117                        (message-y-or-n-p
4118                         (concat "Obey Mail-Followup-To? ") t "\
4119 You should normally obey the Mail-Followup-To: header.  In this
4120 article, it has the value of
4121
4122 " mft "
4123
4124 which directs your response to " (if (string-match "," mft)
4125                                      "the specified addresses"
4126                                    "that address only") ".
4127
4128 Most commonly, Mail-Followup-To is used by a mailing list poster to
4129 express that responses should be sent to just the list, and not the
4130 poster as well.
4131
4132 If a message is posted to several mailing lists, Mail-Followup-To may
4133 also be used to direct the following discussion to one list only,
4134 because discussions that are spread over several lists tend to be
4135 fragmented and very difficult to follow.
4136
4137 Also, some source/announcement lists are not intended for discussion;
4138 responses here are directed to other addresses.")))
4139               (insert mft)
4140             (unless never-mct
4141               (insert (or mrt reply-to from "")))
4142             (insert (if to (concat (if (bolp) "" ", ") to "") ""))
4143             (insert (if mct (concat (if (bolp) "" ", ") mct) ""))
4144             (insert (if cc (concat (if (bolp) "" ", ") cc) "")))
4145           (goto-char (point-min))
4146           (while (re-search-forward "[ \t]+" nil t)
4147             (replace-match " " t t))
4148           ;; Remove addresses that match `rmail-dont-reply-to-names'.
4149           (let ((rmail-dont-reply-to-names message-dont-reply-to-names))
4150             (insert (prog1 (rmail-dont-reply-to (buffer-string))
4151                       (erase-buffer))))
4152           (goto-char (point-min))
4153           ;; Perhaps "Mail-Copies-To: never" removed the only address?
4154           (when (eobp)
4155             (insert (or mrt reply-to from "")))
4156           (setq ccalist
4157                 (mapcar
4158                  (lambda (addr)
4159                    (cons (mail-strip-quoted-names addr) addr))
4160                  (message-tokenize-header (buffer-string))))
4161           (let ((s ccalist))
4162             (while s
4163               (setq ccalist (delq (assoc (car (pop s)) s) ccalist)))))
4164         (setq follow-to (list (cons 'To (cdr (pop ccalist)))))
4165         (when ccalist
4166           (let ((ccs (cons 'Cc (mapconcat
4167                                 (lambda (addr) (cdr addr)) ccalist ", "))))
4168             (when (string-match "^ +" (cdr ccs))
4169               (setcdr ccs (substring (cdr ccs) (match-end 0))))
4170             (push ccs follow-to)))
4171         ;; Allow the user to be asked whether or not to reply to all
4172         ;; recipients in a wide reply.
4173         (if (and ccalist wide message-wide-reply-confirm-recipients
4174                  (not (y-or-n-p "Reply to all recipients? ")))
4175             (setq follow-to (delq (assoc 'Cc follow-to) follow-to)))))
4176     follow-to))
4177
4178
4179 ;;;###autoload
4180 (defun message-reply (&optional to-address wide)
4181   "Start editing a reply to the article in the current buffer."
4182   (interactive)
4183   (require 'gnus-sum)                   ; for gnus-list-identifiers
4184   (let ((cur (current-buffer))
4185         from subject date reply-to to cc
4186         references message-id follow-to
4187         (inhibit-point-motion-hooks t)
4188         (message-this-is-mail t)
4189         gnus-warning)
4190     (save-restriction
4191       (message-narrow-to-head-1)
4192       ;; Allow customizations to have their say.
4193       (if (not wide)
4194           ;; This is a regular reply.
4195           (when (message-functionp message-reply-to-function)
4196             (save-excursion
4197               (setq follow-to (funcall message-reply-to-function))))
4198         ;; This is a followup.
4199         (when (message-functionp message-wide-reply-to-function)
4200           (save-excursion
4201             (setq follow-to
4202                   (funcall message-wide-reply-to-function)))))
4203       (setq message-id (message-fetch-field "message-id" t)
4204             references (message-fetch-field "references")
4205             date (message-fetch-field "date")
4206             from (message-fetch-field "from")
4207             subject (or (message-fetch-field "subject") "none"))
4208       (when gnus-list-identifiers
4209         (setq subject (message-strip-list-identifiers subject)))
4210       (setq subject (concat "Re: " (message-strip-subject-re subject)))
4211
4212       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
4213                  (string-match "<[^>]+>" gnus-warning))
4214         (setq message-id (match-string 0 gnus-warning)))
4215
4216       (unless follow-to
4217         (setq follow-to (message-get-reply-headers wide to-address))))
4218
4219     (unless (message-mail-user-agent)
4220       (message-pop-to-buffer
4221        (message-buffer-name
4222         (if wide "wide reply" "reply") from
4223         (if wide to-address nil))))
4224
4225     (setq message-reply-headers
4226           (vector 0 subject from date message-id references 0 0 ""))
4227
4228     (message-setup
4229      `((Subject . ,subject)
4230        ,@follow-to
4231        ,@(if (or references message-id)
4232              `((References . ,(concat (or references "") (and references " ")
4233                                       (or message-id ""))))
4234            nil))
4235      cur)))
4236
4237 ;;;###autoload
4238 (defun message-wide-reply (&optional to-address)
4239   "Make a \"wide\" reply to the message in the current buffer."
4240   (interactive)
4241   (message-reply to-address t))
4242
4243 ;;;###autoload
4244 (defun message-followup (&optional to-newsgroups)
4245   "Follow up to the message in the current buffer.
4246 If TO-NEWSGROUPS, use that as the new Newsgroups line."
4247   (interactive)
4248   (require 'gnus-sum)                   ; for gnus-list-identifiers
4249   (let ((cur (current-buffer))
4250         from subject date reply-to mrt mct
4251         references message-id follow-to
4252         (inhibit-point-motion-hooks t)
4253         (message-this-is-news t)
4254         followup-to distribution newsgroups gnus-warning posted-to)
4255     (save-restriction
4256       (narrow-to-region
4257        (goto-char (point-min))
4258        (if (search-forward "\n\n" nil t)
4259            (1- (point))
4260          (point-max)))
4261       (when (message-functionp message-followup-to-function)
4262         (setq follow-to
4263               (funcall message-followup-to-function)))
4264       (setq from (message-fetch-field "from")
4265             date (message-fetch-field "date")
4266             subject (or (message-fetch-field "subject") "none")
4267             references (message-fetch-field "references")
4268             message-id (message-fetch-field "message-id" t)
4269             followup-to (message-fetch-field "followup-to")
4270             newsgroups (message-fetch-field "newsgroups")
4271             posted-to (message-fetch-field "posted-to")
4272             reply-to (message-fetch-field "reply-to")
4273             mrt (message-fetch-field "mail-reply-to")
4274             distribution (message-fetch-field "distribution")
4275             mct (message-fetch-field "mail-copies-to"))
4276       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
4277                  (string-match "<[^>]+>" gnus-warning))
4278         (setq message-id (match-string 0 gnus-warning)))
4279       ;; Remove bogus distribution.
4280       (when (and (stringp distribution)
4281                  (let ((case-fold-search t))
4282                    (string-match "world" distribution)))
4283         (setq distribution nil))
4284       (if gnus-list-identifiers
4285           (setq subject (message-strip-list-identifiers subject)))
4286       (setq subject (concat "Re: " (message-strip-subject-re subject)))
4287       (widen))
4288
4289     (message-pop-to-buffer (message-buffer-name "followup" from newsgroups))
4290
4291     (message-setup
4292      `((Subject . ,subject)
4293        ,@(cond
4294           (to-newsgroups
4295            (list (cons 'Newsgroups to-newsgroups)))
4296           (follow-to follow-to)
4297           ((and followup-to message-use-followup-to)
4298            (list
4299             (cond
4300              ((equal (downcase followup-to) "poster")
4301               (if (or (eq message-use-followup-to 'use)
4302                       (message-y-or-n-p "Obey Followup-To: poster? " t "\
4303 You should normally obey the Followup-To: header.
4304
4305 `Followup-To: poster' sends your response via e-mail instead of news.
4306
4307 A typical situation where `Followup-To: poster' is used is when the poster
4308 does not read the newsgroup, so he wouldn't see any replies sent to it."))
4309                   (progn
4310                     (setq message-this-is-news nil)
4311                     (cons 'To (or mrt reply-to from "")))
4312                 (cons 'Newsgroups newsgroups)))
4313              (t
4314               (if (or (equal followup-to newsgroups)
4315                       (not (eq message-use-followup-to 'ask))
4316                       (message-y-or-n-p
4317                        (concat "Obey Followup-To: " followup-to "? ") t "\
4318 You should normally obey the Followup-To: header.
4319
4320         `Followup-To: " followup-to "'
4321 directs your response to " (if (string-match "," followup-to)
4322                                "the specified newsgroups"
4323                              "that newsgroup only") ".
4324
4325 If a message is posted to several newsgroups, Followup-To is often
4326 used to direct the following discussion to one newsgroup only,
4327 because discussions that are spread over several newsgroup tend to
4328 be fragmented and very difficult to follow.
4329
4330 Also, some source/announcement newsgroups are not intended for discussion;
4331 responses here are directed to other newsgroups."))
4332                   (cons 'Newsgroups followup-to)
4333                 (cons 'Newsgroups newsgroups))))))
4334           (posted-to
4335            `((Newsgroups . ,posted-to)))
4336           (t
4337            `((Newsgroups . ,newsgroups))))
4338        ,@(and distribution (list (cons 'Distribution distribution)))
4339        ,@(if (or references message-id)
4340              `((References . ,(concat (or references "") (and references " ")
4341                                       (or message-id "")))))
4342        ,@(when (and mct
4343                     (not (or (equal (downcase mct) "never")
4344                              (equal (downcase mct) "nobody"))))
4345            (list (cons 'Cc (if (or (equal (downcase mct) "always")
4346                                    (equal (downcase mct) "poster"))
4347                                (or mrt reply-to from "")
4348                              mct)))))
4349
4350      cur)
4351
4352     (setq message-reply-headers
4353           (vector 0 subject from date message-id references 0 0 ""))))
4354
4355
4356 ;;;###autoload
4357 (defun message-cancel-news (&optional arg)
4358   "Cancel an article you posted.
4359 If ARG, allow editing of the cancellation message."
4360   (interactive "P")
4361   (unless (message-news-p)
4362     (error "This is not a news article; canceling is impossible"))
4363   (let (from newsgroups message-id distribution buf sender)
4364     (save-excursion
4365       ;; Get header info from original article.
4366       (save-restriction
4367         (message-narrow-to-head-1)
4368         (setq from (message-fetch-field "from")
4369               sender (message-fetch-field "sender")
4370               newsgroups (message-fetch-field "newsgroups")
4371               message-id (message-fetch-field "message-id" t)
4372               distribution (message-fetch-field "distribution")))
4373       ;; Make sure that this article was written by the user.
4374       (unless (or (message-gnksa-enable-p 'cancel-messages)
4375                   (and sender
4376                        (string-equal
4377                         (downcase sender)
4378                         (downcase (message-make-sender))))
4379                   (string-equal
4380                    (downcase (cadr (mail-extract-address-components from)))
4381                    (downcase (cadr (mail-extract-address-components
4382                                     (message-make-from))))))
4383         (error "This article is not yours"))
4384       (when (yes-or-no-p "Do you really want to cancel this article? ")
4385         ;; Make control message.
4386         (if arg
4387             (message-news)
4388           (setq buf (set-buffer (get-buffer-create " *message cancel*"))))
4389         (erase-buffer)
4390         (insert "Newsgroups: " newsgroups "\n"
4391                 "From: " from "\n"
4392                 "Subject: cmsg cancel " message-id "\n"
4393                 "Control: cancel " message-id "\n"
4394                 (if distribution
4395                     (concat "Distribution: " distribution "\n")
4396                   "")
4397                 mail-header-separator "\n"
4398                 message-cancel-message)
4399         (run-hooks 'message-cancel-hook)
4400         (unless arg
4401           (message "Canceling your article...")
4402           (if (let ((message-syntax-checks
4403                      'dont-check-for-anything-just-trust-me))
4404                 (funcall message-send-news-function))
4405               (message "Canceling your article...done"))
4406           (kill-buffer buf))))))
4407
4408 ;;;###autoload
4409 (defun message-supersede ()
4410   "Start composing a message to supersede the current message.
4411 This is done simply by taking the old article and adding a Supersedes
4412 header line with the old Message-ID."
4413   (interactive)
4414   (let ((cur (current-buffer))
4415         (sender (message-fetch-field "sender"))
4416         (from (message-fetch-field "from")))
4417     ;; Check whether the user owns the article that is to be superseded.
4418     (unless (or (message-gnksa-enable-p 'cancel-messages)
4419                 (and sender
4420                      (string-equal
4421                       (downcase sender)
4422                       (downcase (message-make-sender))))
4423                 (string-equal
4424                  (downcase (cadr (mail-extract-address-components from)))
4425                  (downcase (cadr (mail-extract-address-components
4426                                   (message-make-from))))))
4427       (error "This article is not yours"))
4428     ;; Get a normal message buffer.
4429     (message-pop-to-buffer (message-buffer-name "supersede"))
4430     (insert-buffer-substring cur)
4431     (mime-to-mml)
4432     (message-narrow-to-head-1)
4433     ;; Remove unwanted headers.
4434     (when message-ignored-supersedes-headers
4435       (message-remove-header message-ignored-supersedes-headers t))
4436     (goto-char (point-min))
4437     (if (not (re-search-forward "^Message-ID: " nil t))
4438         (error "No Message-ID in this article")
4439       (replace-match "Supersedes: " t t))
4440     (goto-char (point-max))
4441     (insert mail-header-separator)
4442     (widen)
4443     (forward-line 1)))
4444
4445 ;;;###autoload
4446 (defun message-recover ()
4447   "Reread contents of current buffer from its last auto-save file."
4448   (interactive)
4449   (let ((file-name (make-auto-save-file-name)))
4450     (cond ((save-window-excursion
4451              (if (not (eq system-type 'vax-vms))
4452                  (with-output-to-temp-buffer "*Directory*"
4453                    (with-current-buffer standard-output
4454                      (fundamental-mode)) ; for Emacs 20.4+
4455                    (buffer-disable-undo standard-output)
4456                    (let ((default-directory "/"))
4457                      (call-process
4458                       "ls" nil standard-output nil "-l" file-name))))
4459              (yes-or-no-p (format "Recover auto save file %s? " file-name)))
4460            (let ((buffer-read-only nil))
4461              (erase-buffer)
4462              (insert-file-contents file-name nil)))
4463           (t (error "message-recover cancelled")))))
4464
4465 ;;; Washing Subject:
4466
4467 (defun message-wash-subject (subject)
4468   "Remove junk like \"Re:\", \"(fwd)\", etc. added to subject string SUBJECT.
4469 Previous forwarders, replyers, etc. may add it."
4470   (with-temp-buffer
4471     (insert-string subject)
4472     (goto-char (point-min))
4473     ;; strip Re/Fwd stuff off the beginning
4474     (while (re-search-forward
4475             "\\([Rr][Ee]:\\|[Ff][Ww][Dd]\\(\\[[0-9]*\\]\\)?:\\|[Ff][Ww]:\\)" nil t)
4476       (replace-match ""))
4477
4478     ;; and gnus-style forwards [foo@bar.com] subject
4479     (goto-char (point-min))
4480     (while (re-search-forward "\\[[^ \t]*\\(@\\|\\.\\)[^ \t]*\\]" nil t)
4481       (replace-match ""))
4482
4483     ;; and off the end
4484     (goto-char (point-max))
4485     (while (re-search-backward "([Ff][Ww][Dd])" nil t)
4486       (replace-match ""))
4487
4488     ;; and finally, any whitespace that was left-over
4489     (goto-char (point-min))
4490     (while (re-search-forward "^[ \t]+" nil t)
4491       (replace-match ""))
4492     (goto-char (point-max))
4493     (while (re-search-backward "[ \t]+$" nil t)
4494       (replace-match ""))
4495
4496     (buffer-string)))
4497
4498 ;;; Forwarding messages.
4499
4500 (defvar message-forward-decoded-p nil
4501   "Non-nil means the original message is decoded.")
4502
4503 (defun message-forward-subject-author-subject (subject)
4504   "Generate a SUBJECT for a forwarded message.
4505 The form is: [Source] Subject, where if the original message was mail,
4506 Source is the sender, and if the original message was news, Source is
4507 the list of newsgroups is was posted to."
4508   (concat "["
4509           (let ((prefix
4510                  (or (message-fetch-field
4511                       (if (message-news-p) "newsgroups" "from"))
4512                      "(nowhere)")))
4513             (if message-forward-decoded-p
4514                 prefix
4515               (mail-decode-encoded-word-string prefix)))
4516           "] " subject))
4517
4518 (defun message-forward-subject-fwd (subject)
4519   "Generate a SUBJECT for a forwarded message.
4520 The form is: Fwd: Subject, where Subject is the original subject of
4521 the message."
4522   (concat "Fwd: " subject))
4523
4524 (defun message-make-forward-subject ()
4525   "Return a Subject header suitable for the message in the current buffer."
4526   (save-excursion
4527     (save-restriction
4528       (message-narrow-to-head-1)
4529       (let ((funcs message-make-forward-subject-function)
4530             (subject (message-fetch-field "Subject")))
4531         (setq subject
4532               (if subject
4533                   (if message-forward-decoded-p
4534                       subject
4535                     (mail-decode-encoded-word-string subject))
4536                 ""))
4537         (if message-wash-forwarded-subjects
4538             (setq subject (message-wash-subject subject)))
4539         ;; Make sure funcs is a list.
4540         (and funcs
4541              (not (listp funcs))
4542              (setq funcs (list funcs)))
4543         ;; Apply funcs in order, passing subject generated by previous
4544         ;; func to the next one.
4545         (while funcs
4546           (when (message-functionp (car funcs))
4547             (setq subject (funcall (car funcs) subject)))
4548           (setq funcs (cdr funcs)))
4549         subject))))
4550
4551 (eval-when-compile
4552   (defvar gnus-article-decoded-p))
4553
4554 ;;;###autoload
4555 (defun message-forward (&optional news digest)
4556   "Forward the current message via mail.
4557 Optional NEWS will use news to forward instead of mail.
4558 Optional DIGEST will use digest to forward."
4559   (interactive "P")
4560   (let* ((cur (current-buffer))
4561          (message-forward-decoded-p
4562           (if (local-variable-p 'gnus-article-decoded-p (current-buffer))
4563               gnus-article-decoded-p ;; In an article buffer.
4564             message-forward-decoded-p))
4565          (subject (message-make-forward-subject))
4566          art-beg)
4567     (if news
4568         (message-news nil subject)
4569       (message-mail nil subject))
4570     ;; Put point where we want it before inserting the forwarded
4571     ;; message.
4572     (if message-forward-before-signature
4573         (message-goto-body)
4574       (goto-char (point-max)))
4575     (if message-forward-as-mime
4576         (if digest
4577             (insert "\n<#multipart type=digest>\n")
4578           (if message-forward-show-mml
4579               (insert "\n\n<#mml type=message/rfc822 disposition=inline>\n")
4580             (insert "\n\n<#part type=message/rfc822 disposition=inline raw=t>\n")))
4581       (insert "\n-------------------- Start of forwarded message --------------------\n"))
4582     (let ((b (point)) e)
4583       (if digest
4584           (if message-forward-as-mime
4585               (insert-buffer-substring cur)
4586             (mml-insert-buffer cur))
4587         (if (and message-forward-show-mml
4588                  (not message-forward-decoded-p))
4589             (insert
4590              (with-temp-buffer
4591                (mm-disable-multibyte-mule4) ;; Must copy buffer in unibyte mode
4592                (insert
4593                 (with-current-buffer cur
4594                   (mm-string-as-unibyte (buffer-string))))
4595                (mm-enable-multibyte-mule4)
4596                (mime-to-mml)
4597                (goto-char (point-min))
4598                (when (looking-at "From ")
4599                  (replace-match "X-From-Line: "))
4600                (buffer-string)))
4601           (save-restriction
4602             (narrow-to-region (point) (point))
4603             (mml-insert-buffer cur)
4604             (goto-char (point-min))
4605             (when (looking-at "From ")
4606               (replace-match "X-From-Line: "))
4607             (goto-char (point-max)))))
4608       (setq e (point))
4609       (if message-forward-as-mime
4610           (if digest
4611               (insert "<#/multipart>\n")
4612             (if message-forward-show-mml
4613                 (insert "<#/mml>\n")
4614               (insert "<#/part>\n")))
4615         (insert "\n-------------------- End of forwarded message --------------------\n"))
4616       (if (and digest message-forward-as-mime)
4617           (save-restriction
4618             (narrow-to-region b e)
4619             (goto-char b)
4620             (narrow-to-region (point)
4621                               (or (search-forward "\n\n" nil t) (point)))
4622             (delete-region (point-min) (point-max)))
4623         (when (and (not current-prefix-arg)
4624                    message-forward-ignored-headers)
4625           (save-restriction
4626             (narrow-to-region b e)
4627             (goto-char b)
4628             (narrow-to-region (point)
4629                               (or (search-forward "\n\n" nil t) (point)))
4630             (message-remove-header message-forward-ignored-headers t)))))
4631     (message-position-point)))
4632
4633 ;;;###autoload
4634 (defun message-resend (address)
4635   "Resend the current article to ADDRESS."
4636   (interactive
4637    (list (message-read-from-minibuffer "Resend message to: ")))
4638   (message "Resending message to %s..." address)
4639   (save-excursion
4640     (let ((cur (current-buffer))
4641           beg)
4642       ;; We first set up a normal mail buffer.
4643       (unless (message-mail-user-agent)
4644         (set-buffer (get-buffer-create " *message resend*"))
4645         (erase-buffer))
4646       (let ((message-this-is-mail t))
4647         (message-setup `((To . ,address))))
4648       ;; Insert our usual headers.
4649       (message-generate-headers '(From Date To))
4650       (message-narrow-to-headers)
4651       ;; Rename them all to "Resent-*".
4652       (while (re-search-forward "^[A-Za-z]" nil t)
4653         (forward-char -1)
4654         (insert "Resent-"))
4655       (widen)
4656       (forward-line)
4657       (delete-region (point) (point-max))
4658       (setq beg (point))
4659       ;; Insert the message to be resent.
4660       (insert-buffer-substring cur)
4661       (goto-char (point-min))
4662       (search-forward "\n\n")
4663       (forward-char -1)
4664       (save-restriction
4665         (narrow-to-region beg (point))
4666         (message-remove-header message-ignored-resent-headers t)
4667         (goto-char (point-max)))
4668       (insert mail-header-separator)
4669       ;; Rename all old ("Also-")Resent headers.
4670       (while (re-search-backward "^\\(Also-\\)*Resent-" beg t)
4671         (beginning-of-line)
4672         (insert "Also-"))
4673       ;; Quote any "From " lines at the beginning.
4674       (goto-char beg)
4675       (when (looking-at "From ")
4676         (replace-match "X-From-Line: "))
4677       ;; Send it.
4678       (let ((message-inhibit-body-encoding t)
4679             message-required-mail-headers)
4680         (message-send-mail))
4681       (kill-buffer (current-buffer)))
4682     (message "Resending message to %s...done" address)))
4683
4684 ;;;###autoload
4685 (defun message-bounce ()
4686   "Re-mail the current message.
4687 This only makes sense if the current message is a bounce message that
4688 contains some mail you have written which has been bounced back to
4689 you."
4690   (interactive)
4691   (let ((handles (mm-dissect-buffer t))
4692         boundary)
4693     (message-pop-to-buffer (message-buffer-name "bounce"))
4694     (if (stringp (car handles))
4695         ;; This is a MIME bounce.
4696         (mm-insert-part (car (last handles)))
4697       ;; This is a non-MIME bounce, so we try to remove things
4698       ;; manually.
4699       (mm-insert-part handles)
4700       (undo-boundary)
4701       (goto-char (point-min))
4702       (search-forward "\n\n" nil t)
4703       (if (or (and (re-search-forward message-unsent-separator nil t)
4704                    (forward-line 1))
4705               (re-search-forward "^Return-Path:.*\n" nil t))
4706           ;; We remove everything before the bounced mail.
4707           (delete-region
4708            (point-min)
4709            (if (re-search-forward "^[^ \n\t]+:" nil t)
4710                (match-beginning 0)
4711              (point)))
4712         (when (re-search-backward "^.?From .*\n" nil t)
4713           (delete-region (match-beginning 0) (match-end 0)))))
4714     (mm-enable-multibyte)
4715     (mime-to-mml)
4716     (save-restriction
4717       (message-narrow-to-head-1)
4718       (message-remove-header message-ignored-bounced-headers t)
4719       (goto-char (point-max))
4720       (insert mail-header-separator))
4721     (message-position-point)))
4722
4723 ;;;
4724 ;;; Interactive entry points for new message buffers.
4725 ;;;
4726
4727 ;;;###autoload
4728 (defun message-mail-other-window (&optional to subject)
4729   "Like `message-mail' command, but display mail buffer in another window."
4730   (interactive)
4731   (unless (message-mail-user-agent)
4732     (let ((pop-up-windows t)
4733           (special-display-buffer-names nil)
4734           (special-display-regexps nil)
4735           (same-window-buffer-names nil)
4736           (same-window-regexps nil))
4737       (message-pop-to-buffer (message-buffer-name "mail" to))))
4738   (let ((message-this-is-mail t))
4739     (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))
4740                    nil nil 'switch-to-buffer-other-window)))
4741
4742 ;;;###autoload
4743 (defun message-mail-other-frame (&optional to subject)
4744   "Like `message-mail' command, but display mail buffer in another frame."
4745   (interactive)
4746   (unless (message-mail-user-agent)
4747     (let ((pop-up-frames t)
4748           (special-display-buffer-names nil)
4749           (special-display-regexps nil)
4750           (same-window-buffer-names nil)
4751           (same-window-regexps nil))
4752       (message-pop-to-buffer (message-buffer-name "mail" to))))
4753   (let ((message-this-is-mail t))
4754     (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))
4755                    nil nil 'switch-to-buffer-other-frame)))
4756
4757 ;;;###autoload
4758 (defun message-news-other-window (&optional newsgroups subject)
4759   "Start editing a news article to be sent."
4760   (interactive)
4761   (let ((pop-up-windows t)
4762         (special-display-buffer-names nil)
4763         (special-display-regexps nil)
4764         (same-window-buffer-names nil)
4765         (same-window-regexps nil))
4766     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
4767   (let ((message-this-is-news t))
4768     (message-setup `((Newsgroups . ,(or newsgroups ""))
4769                      (Subject . ,(or subject ""))))))
4770
4771 ;;;###autoload
4772 (defun message-news-other-frame (&optional newsgroups subject)
4773   "Start editing a news article to be sent."
4774   (interactive)
4775   (let ((pop-up-frames t)
4776         (special-display-buffer-names nil)
4777         (special-display-regexps nil)
4778         (same-window-buffer-names nil)
4779         (same-window-regexps nil))
4780     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
4781   (let ((message-this-is-news t))
4782     (message-setup `((Newsgroups . ,(or newsgroups ""))
4783                      (Subject . ,(or subject ""))))))
4784
4785 ;;; underline.el
4786
4787 ;; This code should be moved to underline.el (from which it is stolen).
4788
4789 ;;;###autoload
4790 (defun bold-region (start end)
4791   "Bold all nonblank characters in the region.
4792 Works by overstriking characters.
4793 Called from program, takes two arguments START and END
4794 which specify the range to operate on."
4795   (interactive "r")
4796   (save-excursion
4797     (let ((end1 (make-marker)))
4798       (move-marker end1 (max start end))
4799       (goto-char (min start end))
4800       (while (< (point) end1)
4801         (or (looking-at "[_\^@- ]")
4802             (insert (char-after) "\b"))
4803         (forward-char 1)))))
4804
4805 ;;;###autoload
4806 (defun unbold-region (start end)
4807   "Remove all boldness (overstruck characters) in the region.
4808 Called from program, takes two arguments START and END
4809 which specify the range to operate on."
4810   (interactive "r")
4811   (save-excursion
4812     (let ((end1 (make-marker)))
4813       (move-marker end1 (max start end))
4814       (goto-char (min start end))
4815       (while (re-search-forward "\b" end1 t)
4816         (if (eq (char-after) (char-after (- (point) 2)))
4817             (delete-char -2))))))
4818
4819 (defalias 'message-exchange-point-and-mark 'exchange-point-and-mark)
4820
4821 ;; Support for toolbar
4822 (eval-when-compile
4823   (defvar tool-bar-map)
4824   (defvar tool-bar-mode))
4825
4826 (defun message-tool-bar-map ()
4827   (or message-tool-bar-map
4828       (setq message-tool-bar-map
4829             (and (fboundp 'tool-bar-add-item-from-menu)
4830                  tool-bar-mode
4831                  (let ((tool-bar-map (copy-keymap tool-bar-map))
4832                        (load-path (mm-image-load-path)))
4833                    ;; Zap some items which aren't so relevant and take
4834                    ;; up space.
4835                    (dolist (key '(print-buffer kill-buffer save-buffer
4836                                                write-file dired open-file))
4837                      (define-key tool-bar-map (vector key) nil))
4838                    (tool-bar-add-item-from-menu
4839                     'message-send-and-exit "mail_send" message-mode-map)
4840                    (tool-bar-add-item-from-menu
4841                     'message-kill-buffer "close" message-mode-map)
4842                    (tool-bar-add-item-from-menu
4843                     'message-dont-send "cancel" message-mode-map)
4844                    (tool-bar-add-item-from-menu
4845                     'mml-attach-file "attach" message-mode-map)
4846                    (tool-bar-add-item-from-menu
4847                     'ispell-message "spell" message-mode-map)
4848                    tool-bar-map)))))
4849
4850 ;;; Group name completion.
4851
4852 (defvar message-newgroups-header-regexp
4853   "^\\(Newsgroups\\|Followup-To\\|Posted-To\\|Gcc\\):"
4854   "Regexp that match headers that lists groups.")
4855
4856 (defvar message-completion-alist
4857   (list (cons message-newgroups-header-regexp 'message-expand-group)
4858         '("^\\(Resent-\\)?\\(To\\|B?Cc\\):" . message-expand-name))
4859   "Alist of (RE . FUN).  Use FUN for completion on header lines matching RE.")
4860
4861 (defvar message-tab-body-function 'indent-relative
4862   "*Function to execute when `message-tab' (TAB) is executed in the body.")
4863
4864 (defun message-tab ()
4865   "Complete names according to `message-completion-alist'.
4866 Do an `indent-relative' if not in those headers."
4867   (interactive)
4868   (let ((alist message-completion-alist))
4869     (while (and alist
4870                 (let ((mail-abbrev-mode-regexp (caar alist)))
4871                   (not (mail-abbrev-in-expansion-header-p))))
4872       (setq alist (cdr alist)))
4873     (funcall (or (cdar alist) message-tab-body-function))))
4874
4875 (defun message-expand-group ()
4876   "Expand the group name under point."
4877   (let* ((b (save-excursion
4878               (save-restriction
4879                 (narrow-to-region
4880                  (save-excursion
4881                    (beginning-of-line)
4882                    (skip-chars-forward "^:")
4883                    (1+ (point)))
4884                  (point))
4885                 (skip-chars-backward "^, \t\n") (point))))
4886          (completion-ignore-case t)
4887          (string (buffer-substring b (progn (skip-chars-forward "^,\t\n ")
4888                                             (point))))
4889          (hashtb (and (boundp 'gnus-active-hashtb) gnus-active-hashtb))
4890          (completions (all-completions string hashtb))
4891          comp)
4892     (delete-region b (point))
4893     (cond
4894      ((= (length completions) 1)
4895       (if (string= (car completions) string)
4896           (progn
4897             (insert string)
4898             (message "Only matching group"))
4899         (insert (car completions))))
4900      ((and (setq comp (try-completion string hashtb))
4901            (not (string= comp string)))
4902       (insert comp))
4903      (t
4904       (insert string)
4905       (if (not comp)
4906           (message "No matching groups")
4907         (save-selected-window
4908           (pop-to-buffer "*Completions*")
4909           (buffer-disable-undo)
4910           (let ((buffer-read-only nil))
4911             (erase-buffer)
4912             (let ((standard-output (current-buffer)))
4913               (display-completion-list (sort completions 'string<)))
4914             (goto-char (point-min))
4915             (delete-region (point) (progn (forward-line 3) (point))))))))))
4916
4917 (defun message-expand-name ()
4918   (if (fboundp 'bbdb-complete-name)
4919       (bbdb-complete-name)
4920     (expand-abbrev)))
4921
4922 ;;; Help stuff.
4923
4924 (defun message-talkative-question (ask question show &rest text)
4925   "Call FUNCTION with argument QUESTION; optionally display TEXT... args.
4926 If SHOW is non-nil, the arguments TEXT... are displayed in a temp buffer.
4927 The following arguments may contain lists of values."
4928   (if (and show
4929            (setq text (message-flatten-list text)))
4930       (save-window-excursion
4931         (save-excursion
4932           (with-output-to-temp-buffer " *MESSAGE information message*"
4933             (set-buffer " *MESSAGE information message*")
4934             (fundamental-mode)          ; for Emacs 20.4+
4935             (mapcar 'princ text)
4936             (goto-char (point-min))))
4937         (funcall ask question))
4938     (funcall ask question)))
4939
4940 (defun message-flatten-list (list)
4941   "Return a new, flat list that contains all elements of LIST.
4942
4943 \(message-flatten-list '(1 (2 3 (4 5 (6))) 7))
4944 => (1 2 3 4 5 6 7)"
4945   (cond ((consp list)
4946          (apply 'append (mapcar 'message-flatten-list list)))
4947         (list
4948          (list list))))
4949
4950 (defun message-generate-new-buffer-clone-locals (name &optional varstr)
4951   "Create and return a buffer with name based on NAME using `generate-new-buffer.'
4952 Then clone the local variables and values from the old buffer to the
4953 new one, cloning only the locals having a substring matching the
4954 regexp varstr."
4955   (let ((oldbuf (current-buffer)))
4956     (save-excursion
4957       (set-buffer (generate-new-buffer name))
4958       (message-clone-locals oldbuf varstr)
4959       (current-buffer))))
4960
4961 (defun message-clone-locals (buffer &optional varstr)
4962   "Clone the local variables from BUFFER to the current buffer."
4963   (let ((locals (save-excursion
4964                   (set-buffer buffer)
4965                   (buffer-local-variables)))
4966         (regexp "^gnus\\|^nn\\|^message\\|^user-mail-address"))
4967     (mapcar
4968      (lambda (local)
4969        (when (and (consp local)
4970                   (car local)
4971                   (string-match regexp (symbol-name (car local)))
4972                   (or (null varstr)
4973                       (string-match varstr (symbol-name (car local)))))
4974          (ignore-errors
4975            (set (make-local-variable (car local))
4976                 (cdr local)))))
4977      locals)))
4978
4979 ;;; Miscellaneous functions
4980
4981 (defsubst message-replace-chars-in-string (string from to)
4982   (mm-subst-char-in-string from to string))
4983
4984 ;;;
4985 ;;; MIME functions
4986 ;;;
4987
4988 (defvar message-inhibit-body-encoding nil)
4989
4990 (defun message-encode-message-body ()
4991   (unless message-inhibit-body-encoding
4992     (let ((mail-parse-charset (or mail-parse-charset
4993                                   message-default-charset))
4994           (case-fold-search t)
4995           lines content-type-p)
4996       (message-goto-body)
4997       (save-restriction
4998         (narrow-to-region (point) (point-max))
4999         (let ((new (mml-generate-mime)))
5000           (when new
5001             (delete-region (point-min) (point-max))
5002             (insert new)
5003             (goto-char (point-min))
5004             (if (eq (aref new 0) ?\n)
5005                 (delete-char 1)
5006               (search-forward "\n\n")
5007               (setq lines (buffer-substring (point-min) (1- (point))))
5008               (delete-region (point-min) (point))))))
5009       (save-restriction
5010         (message-narrow-to-headers-or-head)
5011         (message-remove-header "Mime-Version")
5012         (goto-char (point-max))
5013         (insert "MIME-Version: 1.0\n")
5014         (when lines
5015           (insert lines))
5016         (setq content-type-p
5017               (or mml-boundary
5018                   (re-search-backward "^Content-Type:" nil t))))
5019       (save-restriction
5020         (message-narrow-to-headers-or-head)
5021         (message-remove-first-header "Content-Type")
5022         (message-remove-first-header "Content-Transfer-Encoding"))
5023       ;; We always make sure that the message has a Content-Type header.
5024       ;; This is because some broken MTAs and MUAs get awfully confused
5025       ;; when confronted with a message with a MIME-Version header and
5026       ;; without a Content-Type header.  For instance, Solaris'
5027       ;; /usr/bin/mail.
5028       (unless content-type-p
5029         (goto-char (point-min))
5030         (re-search-forward "^MIME-Version:")
5031         (forward-line 1)
5032         (insert "Content-Type: text/plain; charset=us-ascii\n")))))
5033
5034 (defun message-read-from-minibuffer (prompt)
5035   "Read from the minibuffer while providing abbrev expansion."
5036   (if (fboundp 'mail-abbrevs-setup)
5037       (let ((mail-abbrev-mode-regexp "")
5038             (minibuffer-setup-hook 'mail-abbrevs-setup)
5039             (minibuffer-local-map message-minibuffer-local-map))
5040         (read-from-minibuffer prompt))
5041     (let ((minibuffer-setup-hook 'mail-abbrev-minibuffer-setup-hook)
5042           (minibuffer-local-map message-minibuffer-local-map))
5043       (read-string prompt))))
5044
5045 (defun message-use-alternative-email-as-from ()
5046   (require 'mail-utils)
5047   (let* ((fields '("To" "Cc"))
5048          (emails
5049           (split-string
5050            (mail-strip-quoted-names
5051             (mapconcat 'message-fetch-reply-field fields ","))
5052            "[ \f\t\n\r\v,]+"))
5053          email)
5054     (while emails
5055       (if (string-match message-alternative-emails (car emails))
5056           (setq email (car emails)
5057                 emails nil))
5058       (pop emails))
5059     (unless (or (not email) (equal email user-mail-address))
5060       (goto-char (point-max))
5061       (insert "From: " email "\n"))))
5062
5063 (defun message-options-get (symbol)
5064   (cdr (assq symbol message-options)))
5065
5066 (defun message-options-set (symbol value)
5067   (let ((the-cons (assq symbol message-options)))
5068     (if the-cons
5069         (if value
5070             (setcdr the-cons value)
5071           (setq message-options (delq the-cons message-options)))
5072       (and value
5073            (push (cons symbol value) message-options))))
5074   value)
5075
5076 (defun message-options-set-recipient ()
5077   (save-restriction
5078     (message-narrow-to-headers-or-head)
5079     (message-options-set 'message-sender
5080                          (mail-strip-quoted-names
5081                           (message-fetch-field "from")))
5082     (message-options-set 'message-recipients
5083                          (mail-strip-quoted-names
5084                           (let ((to (message-fetch-field "to"))
5085                                 (cc (message-fetch-field "cc"))
5086                                 (bcc (message-fetch-field "bcc")))
5087                             (concat
5088                              (or to "")
5089                              (if (and to cc) ", ")
5090                              (or cc "")
5091                              (if (and (or to cc) bcc) ", ")
5092                              (or bcc "")))))))
5093
5094 (when (featurep 'xemacs)
5095   (require 'messagexmas)
5096   (message-xmas-redefine))
5097
5098 (provide 'message)
5099
5100 (run-hooks 'message-load-hook)
5101
5102 ;; Local Variables:
5103 ;; coding: iso-8859-1
5104 ;; End:
5105
5106 ;;; message.el ends here