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