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