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