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