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