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