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