* nnimap.el (nnimap-need-unselect-to-notice-new-mail)
[gnus] / lisp / message.el
1 ;;; message.el --- composing mail and news messages
2 ;; Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002
3 ;;        Free Software Foundation, Inc.
4
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;; Keywords: mail, news
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
13 ;; any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
22 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
24
25 ;;; Commentary:
26
27 ;; This mode provides mail-sending facilities from within Emacs.  It
28 ;; consists mainly of large chunks of code from the sendmail.el,
29 ;; gnus-msg.el and rnewspost.el files.
30
31 ;;; Code:
32
33 (eval-when-compile
34   (require 'cl)
35   (defvar gnus-list-identifiers)) ; gnus-sum is required where necessary
36 (require 'canlock)
37 (require 'mailheader)
38 (require 'nnheader)
39 ;; This is apparently necessary even though things are autoloaded:
40 (if (featurep 'xemacs)
41     (require 'mail-abbrevs))
42 (require 'mail-parse)
43 (require 'mml)
44 (require 'rfc822)
45 (eval-and-compile
46   (autoload 'sha1 "sha1-el"))
47
48 (defgroup message '((user-mail-address custom-variable)
49                     (user-full-name custom-variable))
50   "Mail and news message composing."
51   :link '(custom-manual "(message)Top")
52   :group 'mail
53   :group 'news)
54
55 (put 'user-mail-address 'custom-type 'string)
56 (put 'user-full-name 'custom-type 'string)
57
58 (defgroup message-various nil
59   "Various Message Variables"
60   :link '(custom-manual "(message)Various Message Variables")
61   :group 'message)
62
63 (defgroup message-buffers nil
64   "Message Buffers"
65   :link '(custom-manual "(message)Message Buffers")
66   :group 'message)
67
68 (defgroup message-sending nil
69   "Message Sending"
70   :link '(custom-manual "(message)Sending Variables")
71   :group 'message)
72
73 (defgroup message-interface nil
74   "Message Interface"
75   :link '(custom-manual "(message)Interface")
76   :group 'message)
77
78 (defgroup message-forwarding nil
79   "Message Forwarding"
80   :link '(custom-manual "(message)Forwarding")
81   :group 'message-interface)
82
83 (defgroup message-insertion nil
84   "Message Insertion"
85   :link '(custom-manual "(message)Insertion")
86   :group 'message)
87
88 (defgroup message-headers nil
89   "Message Headers"
90   :link '(custom-manual "(message)Message Headers")
91   :group 'message)
92
93 (defgroup message-news nil
94   "Composing News Messages"
95   :group 'message)
96
97 (defgroup message-mail nil
98   "Composing Mail Messages"
99   :group 'message)
100
101 (defgroup message-faces nil
102   "Faces used for message composing."
103   :group 'message
104   :group 'faces)
105
106 (defcustom message-directory "~/Mail/"
107   "*Directory from which all other mail file variables are derived."
108   :group 'message-various
109   :type 'directory)
110
111 (defcustom message-max-buffers 10
112   "*How many buffers to keep before starting to kill them off."
113   :group 'message-buffers
114   :type 'integer)
115
116 (defcustom message-send-rename-function nil
117   "Function called to rename the buffer after sending it."
118   :group 'message-buffers
119   :type '(choice function (const nil)))
120
121 (defcustom message-fcc-handler-function 'message-output
122   "*A function called to save outgoing articles.
123 This function will be called with the name of the file to store the
124 article in.  The default function is `message-output' which saves in Unix
125 mailbox format."
126   :type '(radio (function-item message-output)
127                 (function :tag "Other"))
128   :group 'message-sending)
129
130 (defcustom message-fcc-externalize-attachments nil
131   "If non-nil, attachments are included as external parts in Fcc copies."
132   :type 'boolean
133   :group 'message-sending)
134
135 (defcustom message-courtesy-message
136   "The following message is a courtesy copy of an article\nthat has been posted to %s as well.\n\n"
137   "*This is inserted at the start of a mailed copy of a posted message.
138 If the string contains the format spec \"%s\", the Newsgroups
139 the article has been posted to will be inserted there.
140 If this variable is nil, no such courtesy message will be added."
141   :group 'message-sending
142   :type 'string)
143
144 (defcustom message-ignored-bounced-headers "^\\(Received\\|Return-Path\\):"
145   "*Regexp that matches headers to be removed in resent bounced mail."
146   :group 'message-interface
147   :type 'regexp)
148
149 ;;;###autoload
150 (defcustom message-from-style 'default
151   "*Specifies how \"From\" headers look.
152
153 If nil, they contain just the return address like:
154         king@grassland.com
155 If `parens', they look like:
156         king@grassland.com (Elvis Parsley)
157 If `angles', they look like:
158         Elvis Parsley <king@grassland.com>
159
160 Otherwise, most addresses look like `angles', but they look like
161 `parens' if `angles' would need quoting and `parens' would not."
162   :type '(choice (const :tag "simple" nil)
163                  (const parens)
164                  (const angles)
165                  (const default))
166   :group 'message-headers)
167
168 (defcustom message-syntax-checks nil
169   ;; Guess this one shouldn't be easy to customize...
170   "*Controls what syntax checks should not be performed on outgoing posts.
171 To disable checking of long signatures, for instance, add
172  `(signature . disabled)' to this list.
173
174 Don't touch this variable unless you really know what you're doing.
175
176 Checks include `subject-cmsg', `multiple-headers', `sendsys',
177 `message-id', `from', `long-lines', `control-chars', `size',
178 `new-text', `quoting-style', `redirected-followup', `signature',
179 `approved', `sender', `empty', `empty-headers', `message-id', `from',
180 `subject', `shorten-followup-to', `existing-newsgroups',
181 `buffer-file-name', `unchanged', `newsgroups', `reply-to'."
182   :group 'message-news
183   :type '(repeat sexp))                 ; Fixme: improve this
184
185 (defcustom message-required-news-headers
186   '(From Newsgroups Subject Date Message-ID
187          (optional . Organization) Lines
188          (optional . User-Agent))
189   "*Headers to be generated or prompted for when posting an article.
190 RFC977 and RFC1036 require From, Date, Newsgroups, Subject,
191 Message-ID.  Organization, Lines, In-Reply-To, Expires, and
192 User-Agent are optional.  If don't you want message to insert some
193 header, remove it from this list."
194   :group 'message-news
195   :group 'message-headers
196   :type '(repeat sexp))
197
198 (defcustom message-required-mail-headers
199   '(From Subject Date (optional . In-Reply-To) Message-ID Lines
200          (optional . User-Agent))
201   "*Headers to be generated or prompted for when mailing a message.
202 It is recommended that From, Date, To, Subject and Message-ID be
203 included.  Organization, Lines and User-Agent are optional."
204   :group 'message-mail
205   :group 'message-headers
206   :type '(repeat sexp))
207
208 (defcustom message-deletable-headers '(Message-ID Date Lines)
209   "Headers to be deleted if they already exist and were generated by message previously."
210   :group 'message-headers
211   :type 'sexp)
212
213 (defcustom message-ignored-news-headers
214   "^NNTP-Posting-Host:\\|^Xref:\\|^[BGF]cc:\\|^Resent-Fcc:\\|^X-Draft-From:\\|^X-Gnus-Agent-Meta-Information:"
215   "*Regexp of headers to be removed unconditionally before posting."
216   :group 'message-news
217   :group 'message-headers
218   :type 'regexp)
219
220 (defcustom message-ignored-mail-headers
221   "^[GF]cc:\\|^Resent-Fcc:\\|^Xref:\\|^X-Draft-From:\\|^X-Gnus-Agent-Meta-Information:"
222   "*Regexp of headers to be removed unconditionally before mailing."
223   :group 'message-mail
224   :group 'message-headers
225   :type 'regexp)
226
227 (defcustom message-ignored-supersedes-headers "^Path:\\|^Date\\|^NNTP-Posting-Host:\\|^Xref:\\|^Lines:\\|^Received:\\|^X-From-Line:\\|^X-Trace:\\|^X-Complaints-To:\\|Return-Path:\\|^Supersedes:\\|^NNTP-Posting-Date:\\|^X-Trace:\\|^X-Complaints-To:\\|^Cancel-Lock:\\|^Cancel-Key:"
228   "*Header lines matching this regexp will be deleted before posting.
229 It's best to delete old Path and Date headers before posting to avoid
230 any confusion."
231   :group 'message-interface
232   :type 'regexp)
233
234 (defcustom message-subject-re-regexp "^[ \t]*\\([Rr][Ee]:[ \t]*\\)*[ \t]*"
235   "*Regexp matching \"Re: \" in the subject line."
236   :group 'message-various
237   :type 'regexp)
238
239 ;;;###autoload
240 (defcustom message-signature-separator "^-- *$"
241   "Regexp matching the signature separator."
242   :type 'regexp
243   :group 'message-various)
244
245 (defcustom message-elide-ellipsis "\n[...]\n\n"
246   "*The string which is inserted for elided text."
247   :type 'string
248   :group 'message-various)
249
250 (defcustom message-interactive nil
251   "Non-nil means when sending a message wait for and display errors.
252 nil means let mailer mail back a message to report errors."
253   :group 'message-sending
254   :group 'message-mail
255   :type 'boolean)
256
257 (defcustom message-generate-new-buffers 'unique
258   "*Non-nil means create a new message buffer whenever `message-setup' is called.
259 If this is a function, call that function with three parameters:  The type,
260 the to address and the group name.  (Any of these may be nil.)  The function
261 should return the new buffer name."
262   :group 'message-buffers
263   :type '(choice (const :tag "off" nil)
264                  (const :tag "unique" unique)
265                  (const :tag "unsent" unsent)
266                  (function fun)))
267
268 (defcustom message-kill-buffer-on-exit nil
269   "*Non-nil means that the message buffer will be killed after sending a message."
270   :group 'message-buffers
271   :type 'boolean)
272
273 (eval-when-compile
274   (defvar gnus-local-organization))
275 (defcustom message-user-organization
276   (or (and (boundp 'gnus-local-organization)
277            (stringp gnus-local-organization)
278            gnus-local-organization)
279       (getenv "ORGANIZATION")
280       t)
281   "*String to be used as an Organization header.
282 If t, use `message-user-organization-file'."
283   :group 'message-headers
284   :type '(choice string
285                  (const :tag "consult file" t)))
286
287 ;;;###autoload
288 (defcustom message-user-organization-file "/usr/lib/news/organization"
289   "*Local news organization file."
290   :type 'file
291   :group 'message-headers)
292
293 (defcustom message-make-forward-subject-function
294   'message-forward-subject-author-subject
295   "*List of functions called to generate subject headers for forwarded messages.
296 The subject generated by the previous function is passed into each
297 successive function.
298
299 The provided functions are:
300
301 * `message-forward-subject-author-subject' (Source of article (author or
302       newsgroup)), in brackets followed by the subject
303 * `message-forward-subject-fwd' (Subject of article with 'Fwd:' prepended
304       to it."
305   :group 'message-forwarding
306   :type '(radio (function-item message-forward-subject-author-subject)
307                 (function-item message-forward-subject-fwd)
308                 (repeat :tag "List of functions" function)))
309
310 (defcustom message-forward-as-mime t
311   "*If non-nil, forward messages as an inline/rfc822 MIME section.  Otherwise, directly inline the old message in the forwarded message."
312   :version "21.1"
313   :group 'message-forwarding
314   :type 'boolean)
315
316 (defcustom message-forward-show-mml t
317   "*If non-nil, forward messages are shown as mml.  Otherwise, forward messages are unchanged."
318   :version "21.1"
319   :group 'message-forwarding
320   :type 'boolean)
321
322 (defcustom message-forward-before-signature t
323   "*If non-nil, put forwarded message before signature, else after."
324   :group 'message-forwarding
325   :type 'boolean)
326
327 (defcustom message-wash-forwarded-subjects nil
328   "*If non-nil, try to remove as much old cruft as possible from the subject of messages before generating the new subject of a forward."
329   :group 'message-forwarding
330   :type 'boolean)
331
332 (defcustom message-ignored-resent-headers "^Return-receipt\\|^X-Gnus\\|^Gnus-Warning:"
333   "*All headers that match this regexp will be deleted when resending a message."
334   :group 'message-interface
335   :type 'regexp)
336
337 (defcustom message-forward-ignored-headers "^Content-Transfer-Encoding:\\|^X-Gnus"
338   "*All headers that match this regexp will be deleted when forwarding a message."
339   :version "21.1"
340   :group 'message-forwarding
341   :type '(choice (const :tag "None" nil)
342                  regexp))
343
344 (defcustom message-ignored-cited-headers "."
345   "*Delete these headers from the messages you yank."
346   :group 'message-insertion
347   :type 'regexp)
348
349 (defcustom message-cite-prefix-regexp
350   (if (string-match "[[:digit:]]" "1") ;; support POSIX?
351       "\\([ \t]*[-_.[:word:]]+>+\\|[ \t]*[]>»|:}+]\\)+"
352     ;; ?-, ?_ or ?. MUST NOT be in syntax entry w.
353     "\\([ \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-o" 'message-goto-from)
1520   (define-key message-mode-map "\C-c\C-f\C-b" 'message-goto-bcc)
1521   (define-key message-mode-map "\C-c\C-f\C-w" 'message-goto-fcc)
1522   (define-key message-mode-map "\C-c\C-f\C-c" 'message-goto-cc)
1523   (define-key message-mode-map "\C-c\C-f\C-s" 'message-goto-subject)
1524   (define-key message-mode-map "\C-c\C-f\C-r" 'message-goto-reply-to)
1525   (define-key message-mode-map "\C-c\C-f\C-n" 'message-goto-newsgroups)
1526   (define-key message-mode-map "\C-c\C-f\C-d" 'message-goto-distribution)
1527   (define-key message-mode-map "\C-c\C-f\C-f" 'message-goto-followup-to)
1528   (define-key message-mode-map "\C-c\C-f\C-m" 'message-goto-mail-followup-to)
1529   (define-key message-mode-map "\C-c\C-f\C-k" 'message-goto-keywords)
1530   (define-key message-mode-map "\C-c\C-f\C-u" 'message-goto-summary)
1531   (define-key message-mode-map "\C-c\C-f\C-i" 'message-insert-or-toggle-importance)
1532   (define-key message-mode-map "\C-c\C-b" 'message-goto-body)
1533   (define-key message-mode-map "\C-c\C-i" 'message-goto-signature)
1534
1535   (define-key message-mode-map "\C-c\C-t" 'message-insert-to)
1536   (define-key message-mode-map "\C-c\C-n" 'message-insert-newsgroups)
1537
1538   (define-key message-mode-map "\C-c\C-u" 'message-insert-or-toggle-importance)
1539   (define-key message-mode-map "\C-c\M-n" 'message-insert-disposition-notification-to)
1540
1541   (define-key message-mode-map "\C-c\C-y" 'message-yank-original)
1542   (define-key message-mode-map "\C-c\M-\C-y" 'message-yank-buffer)
1543   (define-key message-mode-map "\C-c\C-q" 'message-fill-yanked-message)
1544   (define-key message-mode-map "\C-c\C-w" 'message-insert-signature)
1545   (define-key message-mode-map "\C-c\M-h" 'message-insert-headers)
1546   (define-key message-mode-map "\C-c\C-r" 'message-caesar-buffer-body)
1547   (define-key message-mode-map "\C-c\C-o" 'message-sort-headers)
1548   (define-key message-mode-map "\C-c\M-r" 'message-rename-buffer)
1549
1550   (define-key message-mode-map "\C-c\C-c" 'message-send-and-exit)
1551   (define-key message-mode-map "\C-c\C-s" 'message-send)
1552   (define-key message-mode-map "\C-c\C-k" 'message-kill-buffer)
1553   (define-key message-mode-map "\C-c\C-d" 'message-dont-send)
1554   (define-key message-mode-map "\C-c\n" 'gnus-delay-article)
1555
1556   (define-key message-mode-map "\C-c\C-e" 'message-elide-region)
1557   (define-key message-mode-map "\C-c\C-v" 'message-delete-not-region)
1558   (define-key message-mode-map "\C-c\C-z" 'message-kill-to-signature)
1559   (define-key message-mode-map "\M-\r" 'message-newline-and-reformat)
1560   ;;(define-key message-mode-map "\M-q" 'message-fill-paragraph)
1561
1562   (define-key message-mode-map "\C-c\C-a" 'mml-attach-file)
1563   
1564   (define-key message-mode-map "\C-a" 'message-beginning-of-line)
1565   (define-key message-mode-map "\t" 'message-tab)
1566   (define-key message-mode-map "\M-;" 'comment-region))
1567
1568 (easy-menu-define
1569   message-mode-menu message-mode-map "Message Menu."
1570   `("Message"
1571     ["Sort Headers" message-sort-headers t]
1572     ["Yank Original" message-yank-original t]
1573     ["Fill Yanked Message" message-fill-yanked-message t]
1574     ["Insert Signature" message-insert-signature t]
1575     ["Caesar (rot13) Message" message-caesar-buffer-body t]
1576     ["Caesar (rot13) Region" message-caesar-region (mark t)]
1577     ["Elide Region" message-elide-region (mark t)]
1578     ["Delete Outside Region" message-delete-not-region (mark t)]
1579     ["Kill To Signature" message-kill-to-signature t]
1580     ["Newline and Reformat" message-newline-and-reformat t]
1581     ["Rename buffer" message-rename-buffer t]
1582     ["Flag As Important" message-insert-importance-high
1583      ,@(if (featurep 'xemacs) '(t)
1584          '(:help "Mark this message as important"))]
1585     ["Flag As Unimportant" message-insert-importance-low
1586      ,@(if (featurep 'xemacs) '(t)
1587          '(:help "Mark this message as unimportant"))]
1588     ["Request Receipt" 
1589      message-insert-disposition-notification-to
1590      ,@(if (featurep 'xemacs) '(t)
1591          '(:help "Request a Disposition Notification of this article"))]
1592     ["Spellcheck" ispell-message
1593      ,@(if (featurep 'xemacs) '(t)
1594          '(:help "Spellcheck this message"))]
1595     "----"
1596     ["Send Message" message-send-and-exit
1597      ,@(if (featurep 'xemacs) '(t)
1598          '(:help "Send this message"))]
1599     ["Postpone Message" message-dont-send
1600      ,@(if (featurep 'xemacs) '(t)
1601          '(:help "File this draft message and exit"))]
1602     ["Send at Specific Time" gnus-delay-article
1603      ,@(if (featurep 'xemacs) '(t)
1604          '(:help "Ask, then arrange to send message at that time"))]
1605     ["Kill Message" message-kill-buffer
1606      ,@(if (featurep 'xemacs) '(t)
1607          '(:help "Delete this message without sending"))]))
1608
1609 (easy-menu-define
1610   message-mode-field-menu message-mode-map ""
1611   '("Field"
1612     ["Fetch To" message-insert-to t]
1613     ["Fetch Newsgroups" message-insert-newsgroups t]
1614     "----"
1615     ["To" message-goto-to t]
1616     ["From" message-goto-from t]
1617     ["Subject" message-goto-subject t]
1618     ["Cc" message-goto-cc t]
1619     ["Reply-To" message-goto-reply-to t]
1620     ["Summary" message-goto-summary t]
1621     ["Keywords" message-goto-keywords t]
1622     ["Newsgroups" message-goto-newsgroups t]
1623     ["Followup-To" message-goto-followup-to t]
1624     ["Mail-Followup-To" message-goto-mail-followup-to t]
1625     ["Distribution" message-goto-distribution t]
1626     ["Body" message-goto-body t]
1627     ["Signature" message-goto-signature t]))
1628
1629 (defvar message-tool-bar-map nil)
1630
1631 (eval-when-compile
1632   (defvar facemenu-add-face-function)
1633   (defvar facemenu-remove-face-function))
1634
1635 ;;; Forbidden properties
1636 ;;
1637 ;; We use `after-change-functions' to keep special text properties
1638 ;; that interfer with the normal function of message mode out of the
1639 ;; buffer. 
1640
1641 (defcustom message-strip-special-text-properties t
1642   "Strip special properties from the message buffer.
1643
1644 Emacs has a number of special text properties which can break message
1645 composing in various ways.  If this option is set, message will strip
1646 these properties from the message composition buffer.  However, some
1647 packages requires these properties to be present in order to work.
1648 If you use one of these packages, turn this option off, and hope the
1649 message composition doesn't break too bad."
1650   :group 'message-various
1651   :type 'boolean)
1652
1653 (defconst message-forbidden-properties 
1654   ;; No reason this should be clutter up customize.  We make it a
1655   ;; property list (rather than a list of property symbols), to be
1656   ;; directly useful for `remove-text-properties'.
1657   '(field nil read-only nil intangible nil invisible nil 
1658           mouse-face nil modification-hooks nil insert-in-front-hooks nil
1659           insert-behind-hooks nil point-entered nil point-left nil) 
1660   ;; Other special properties:
1661   ;; category, face, display: probably doesn't do any harm.
1662   ;; fontified: is used by font-lock.
1663   ;; syntax-table, local-map: I dunno.
1664   ;; We need to add XEmacs names to the list.
1665   "Property list of with properties.forbidden in message buffers.
1666 The values of the properties are ignored, only the property names are used.")
1667
1668 (defun message-tamago-not-in-use-p (pos)
1669   "Return t when tamago version 4 is not in use at the cursor position.
1670 Tamago version 4 is a popular input method for writing Japanese text.
1671 It uses the properties `intangible', `invisible', `modification-hooks'
1672 and `read-only' when translating ascii or kana text to kanji text.
1673 These properties are essential to work, so we should never strip them."
1674   (not (and (boundp 'egg-modefull-mode)
1675             (symbol-value 'egg-modefull-mode)
1676             (or (memq (get-text-property pos 'intangible)
1677                       '(its-part-1 its-part-2))
1678                 (get-text-property pos 'egg-end)
1679                 (get-text-property pos 'egg-lang)
1680                 (get-text-property pos 'egg-start)))))
1681
1682 (defun message-strip-forbidden-properties (begin end &optional old-length)
1683   "Strip forbidden properties between BEGIN and END, ignoring the third arg.
1684 This function is intended to be called from `after-change-functions'.
1685 See also `message-forbidden-properties'."
1686   (when (and message-strip-special-text-properties
1687              (message-tamago-not-in-use-p begin))
1688     (remove-text-properties begin end message-forbidden-properties)))
1689
1690 ;;;###autoload
1691 (define-derived-mode message-mode text-mode "Message"
1692   "Major mode for editing mail and news to be sent.
1693 Like Text Mode but with these additional commands:\\<message-mode-map>
1694 C-c C-s  `message-send' (send the message)  C-c C-c  `message-send-and-exit'
1695 C-c C-d  Postpone sending the message       C-c C-k  Kill the message
1696 C-c C-f  move to a header field (and create it if there isn't):
1697          C-c C-f C-t  move to To        C-c C-f C-s  move to Subject
1698          C-c C-f C-c  move to Cc        C-c C-f C-b  move to Bcc
1699          C-c C-f C-w  move to Fcc       C-c C-f C-r  move to Reply-To
1700          C-c C-f C-u  move to Summary   C-c C-f C-n  move to Newsgroups
1701          C-c C-f C-k  move to Keywords  C-c C-f C-d  move to Distribution
1702          C-c C-f C-f  move to Followup-To
1703          C-c C-f C-m  move to Mail-Followup-To
1704          C-c C-f C-i  cycle through Importance values
1705 C-c C-t  `message-insert-to' (add a To header to a news followup)
1706 C-c C-n  `message-insert-newsgroups' (add a Newsgroup header to a news reply)
1707 C-c C-b  `message-goto-body' (move to beginning of message text).
1708 C-c C-i  `message-goto-signature' (move to the beginning of the signature).
1709 C-c C-w  `message-insert-signature' (insert `message-signature-file' file).
1710 C-c C-y  `message-yank-original' (insert current message, if any).
1711 C-c C-q  `message-fill-yanked-message' (fill what was yanked).
1712 C-c C-e  `message-elide-region' (elide the text between point and mark).
1713 C-c C-v  `message-delete-not-region' (remove the text outside the region).
1714 C-c C-z  `message-kill-to-signature' (kill the text up to the signature).
1715 C-c C-r  `message-caesar-buffer-body' (rot13 the message body).
1716 C-c C-a  `mml-attach-file' (attach a file as MIME).
1717 C-c C-u  `message-insert-or-toggle-importance'  (insert or cycle importance).
1718 C-c M-n  `message-insert-disposition-notification-to'  (request receipt).
1719 M-RET    `message-newline-and-reformat' (break the line and reformat)."
1720   (set (make-local-variable 'message-reply-buffer) nil)
1721   (make-local-variable 'message-send-actions)
1722   (make-local-variable 'message-exit-actions)
1723   (make-local-variable 'message-kill-actions)
1724   (make-local-variable 'message-postpone-actions)
1725   (make-local-variable 'message-draft-article)
1726   (setq buffer-offer-save t)
1727   (set (make-local-variable 'facemenu-add-face-function)
1728        (lambda (face end)
1729          (let ((face-fun (cdr (assq face message-face-alist))))
1730            (if face-fun
1731                (funcall face-fun (point) end)
1732              (error "Face %s not configured for %s mode" face mode-name)))
1733          ""))
1734   (set (make-local-variable 'facemenu-remove-face-function) t)
1735   (set (make-local-variable 'message-reply-headers) nil)
1736   (make-local-variable 'message-newsreader)
1737   (make-local-variable 'message-mailer)
1738   (make-local-variable 'message-post-method)
1739   (set (make-local-variable 'message-sent-message-via) nil)
1740   (set (make-local-variable 'message-checksum) nil)
1741   (set (make-local-variable 'message-mime-part) 0)
1742   (message-setup-fill-variables)
1743   ;; Allow using comment commands to add/remove quoting.
1744   (set (make-local-variable 'comment-start) message-yank-prefix)
1745   (if (featurep 'xemacs)
1746       (message-setup-toolbar)
1747     (set (make-local-variable 'font-lock-defaults)
1748          '(message-font-lock-keywords t))
1749     (if (boundp 'tool-bar-map)
1750         (set (make-local-variable 'tool-bar-map) (message-tool-bar-map))))
1751   (easy-menu-add message-mode-menu message-mode-map)
1752   (easy-menu-add message-mode-field-menu message-mode-map)
1753   ;; make-local-hook is harmless though obsolete in Emacs 21.
1754   ;; Emacs 20 and XEmacs need make-local-hook. 
1755   (make-local-hook 'after-change-functions)
1756   ;; Mmmm... Forbidden properties...
1757   (add-hook 'after-change-functions 'message-strip-forbidden-properties 
1758             nil 'local)
1759   ;; Allow mail alias things.
1760   (when (eq message-mail-alias-type 'abbrev)
1761     (if (fboundp 'mail-abbrevs-setup)
1762         (mail-abbrevs-setup)
1763       (mail-aliases-setup)))
1764   (message-set-auto-save-file-name)
1765   (mm-enable-multibyte)
1766   (set (make-local-variable 'indent-tabs-mode) nil) ;No tabs for indentation.
1767   (mml-mode))
1768
1769 (defun message-setup-fill-variables ()
1770   "Setup message fill variables."
1771   (set (make-local-variable 'fill-paragraph-function)
1772        'message-fill-paragraph)
1773   (make-local-variable 'paragraph-separate)
1774   (make-local-variable 'paragraph-start)
1775   (make-local-variable 'adaptive-fill-regexp)
1776   (unless (boundp 'adaptive-fill-first-line-regexp)
1777     (setq adaptive-fill-first-line-regexp nil))
1778   (make-local-variable 'adaptive-fill-first-line-regexp)
1779   (let ((quote-prefix-regexp
1780          ;; User should change message-cite-prefix-regexp if
1781          ;; message-yank-prefix is set to an abnormal value.
1782          (concat "\\(" message-cite-prefix-regexp "\\)[ \t]*")))
1783     (setq paragraph-start
1784           (concat
1785            (regexp-quote mail-header-separator) "$\\|"
1786            "[ \t]*$\\|"                 ; blank lines
1787            "-- $\\|"                    ; signature delimiter
1788            "---+$\\|"              ; delimiters for forwarded messages
1789            page-delimiter "$\\|"        ; spoiler warnings
1790            ".*wrote:$\\|"               ; attribution lines
1791            quote-prefix-regexp "$"))    ; empty lines in quoted text
1792     (setq paragraph-separate paragraph-start)
1793     (setq adaptive-fill-regexp
1794           (concat quote-prefix-regexp "\\|" adaptive-fill-regexp))
1795     (setq adaptive-fill-first-line-regexp
1796           (concat quote-prefix-regexp "\\|"
1797                   adaptive-fill-first-line-regexp)))
1798   (make-local-variable 'auto-fill-inhibit-regexp)
1799   ;;(setq auto-fill-inhibit-regexp "^[A-Z][^: \n\t]+:")
1800   (setq auto-fill-inhibit-regexp nil)
1801   (make-local-variable 'normal-auto-fill-function)
1802   (setq normal-auto-fill-function 'message-do-auto-fill)
1803   ;; KLUDGE: auto fill might already be turned on in `text-mode-hook'.
1804   ;; In that case, ensure that it uses the right function.  The real
1805   ;; solution would be not to use `define-derived-mode', and run
1806   ;; `text-mode-hook' ourself at the end of the mode.
1807   ;; -- Per Abrahamsen <abraham@dina.kvl.dk> Date: 2001-10-19.
1808   (when auto-fill-function
1809     (setq auto-fill-function normal-auto-fill-function)))
1810
1811 \f
1812
1813 ;;;
1814 ;;; Message mode commands
1815 ;;;
1816
1817 ;;; Movement commands
1818
1819 (defun message-goto-to ()
1820   "Move point to the To header."
1821   (interactive)
1822   (message-position-on-field "To"))
1823
1824 (defun message-goto-from ()
1825   "Move point to the From header."
1826   (interactive)
1827   (message-position-on-field "From"))
1828
1829 (defun message-goto-subject ()
1830   "Move point to the Subject header."
1831   (interactive)
1832   (message-position-on-field "Subject"))
1833
1834 (defun message-goto-cc ()
1835   "Move point to the Cc header."
1836   (interactive)
1837   (message-position-on-field "Cc" "To"))
1838
1839 (defun message-goto-bcc ()
1840   "Move point to the Bcc  header."
1841   (interactive)
1842   (message-position-on-field "Bcc" "Cc" "To"))
1843
1844 (defun message-goto-fcc ()
1845   "Move point to the Fcc header."
1846   (interactive)
1847   (message-position-on-field "Fcc" "To" "Newsgroups"))
1848
1849 (defun message-goto-reply-to ()
1850   "Move point to the Reply-To header."
1851   (interactive)
1852   (message-position-on-field "Reply-To" "Subject"))
1853
1854 (defun message-goto-newsgroups ()
1855   "Move point to the Newsgroups header."
1856   (interactive)
1857   (message-position-on-field "Newsgroups"))
1858
1859 (defun message-goto-distribution ()
1860   "Move point to the Distribution header."
1861   (interactive)
1862   (message-position-on-field "Distribution"))
1863
1864 (defun message-goto-followup-to ()
1865   "Move point to the Followup-To header."
1866   (interactive)
1867   (message-position-on-field "Followup-To" "Newsgroups"))
1868
1869 (defun message-goto-mail-followup-to ()
1870   "Move point to the Mail-Followup-To header."
1871   (interactive)
1872   (message-position-on-field "Mail-Followup-To" "From"))
1873
1874 (defun message-goto-keywords ()
1875   "Move point to the Keywords header."
1876   (interactive)
1877   (message-position-on-field "Keywords" "Subject"))
1878
1879 (defun message-goto-summary ()
1880   "Move point to the Summary header."
1881   (interactive)
1882   (message-position-on-field "Summary" "Subject"))
1883
1884 (defun message-goto-body (&optional interactivep)
1885   "Move point to the beginning of the message body."
1886   (interactive (list t))
1887   (when (and interactivep
1888              (looking-at "[ \t]*\n"))
1889     (expand-abbrev))
1890   (goto-char (point-min))
1891   (or (search-forward (concat "\n" mail-header-separator "\n") nil t)
1892       (search-forward-regexp "[^:]+:\\([^\n]\\|\n[ \t]\\)+\n\n" nil t)))
1893
1894 (defun message-goto-eoh ()
1895   "Move point to the end of the headers."
1896   (interactive)
1897   (message-goto-body)
1898   (forward-line -1))
1899
1900 (defun message-goto-signature ()
1901   "Move point to the beginning of the message signature.
1902 If there is no signature in the article, go to the end and
1903 return nil."
1904   (interactive)
1905   (goto-char (point-min))
1906   (if (re-search-forward message-signature-separator nil t)
1907       (forward-line 1)
1908     (goto-char (point-max))
1909     nil))
1910
1911 \f
1912
1913 (defun message-insert-to (&optional force)
1914   "Insert a To header that points to the author of the article being replied to.
1915 If the original author requested not to be sent mail, the function signals
1916 an error.
1917 With the prefix argument FORCE, insert the header anyway."
1918   (interactive "P")
1919   (let ((co (message-fetch-reply-field "mail-copies-to")))
1920     (when (and (null force)
1921                co
1922                (or (equal (downcase co) "never")
1923                    (equal (downcase co) "nobody")))
1924       (error "The user has requested not to have copies sent via mail")))
1925   (when (and (message-position-on-field "To")
1926              (mail-fetch-field "to")
1927              (not (string-match "\\` *\\'" (mail-fetch-field "to"))))
1928     (insert ", "))
1929   (insert (or (message-fetch-reply-field "mail-reply-to")
1930               (message-fetch-reply-field "reply-to")
1931               (message-fetch-reply-field "from") "")))
1932
1933 (defun message-widen-reply ()
1934   "Widen the reply to include maximum recipients."
1935   (interactive)
1936   (let ((follow-to
1937          (and message-reply-buffer
1938               (buffer-name message-reply-buffer)
1939               (save-excursion
1940                 (set-buffer message-reply-buffer)
1941                 (message-get-reply-headers t)))))
1942     (save-excursion
1943       (save-restriction
1944         (message-narrow-to-headers)
1945         (dolist (elem follow-to)
1946           (message-remove-header (symbol-name (car elem)))
1947           (goto-char (point-min))
1948           (insert (symbol-name (car elem)) ": "
1949                   (cdr elem) "\n"))))))
1950
1951 (defun message-insert-newsgroups ()
1952   "Insert the Newsgroups header from the article being replied to."
1953   (interactive)
1954   (when (and (message-position-on-field "Newsgroups")
1955              (mail-fetch-field "newsgroups")
1956              (not (string-match "\\` *\\'" (mail-fetch-field "newsgroups"))))
1957     (insert ","))
1958   (insert (or (message-fetch-reply-field "newsgroups") "")))
1959
1960 \f
1961
1962 ;;; Various commands
1963
1964 (defun message-delete-not-region (beg end)
1965   "Delete everything in the body of the current message outside of the region."
1966   (interactive "r")
1967   (let (citeprefix)
1968     (save-excursion
1969       (goto-char beg)
1970       ;; snarf citation prefix, if appropriate
1971       (unless (eq (point) (progn (beginning-of-line) (point)))
1972         (when (looking-at message-cite-prefix-regexp)
1973           (setq citeprefix (match-string 0))))
1974       (goto-char end)
1975       (delete-region (point) (if (not (message-goto-signature))
1976                                  (point)
1977                                (forward-line -2)
1978                                (point)))
1979       (insert "\n")
1980       (goto-char beg)
1981       (delete-region beg (progn (message-goto-body)
1982                                 (forward-line 2)
1983                                 (point)))
1984       (when citeprefix
1985         (insert citeprefix))))
1986   (when (message-goto-signature)
1987     (forward-line -2)))
1988
1989 (defun message-kill-to-signature ()
1990   "Deletes all text up to the signature."
1991   (interactive)
1992   (let ((point (point)))
1993     (message-goto-signature)
1994     (unless (eobp)
1995       (forward-line -2))
1996     (kill-region point (point))
1997     (unless (bolp)
1998       (insert "\n"))))
1999
2000 (defun message-newline-and-reformat (&optional arg not-break)
2001   "Insert four newlines, and then reformat if inside quoted text.
2002 Prefix arg means justify as well."
2003   (interactive (list (if current-prefix-arg 'full)))
2004   (let (quoted point beg end leading-space bolp)
2005     (setq point (point))
2006     (beginning-of-line)
2007     (setq beg (point))
2008     (setq bolp (= beg point))
2009     ;; Find first line of the paragraph.
2010     (if not-break
2011         (while (and (not (eobp))
2012                     (not (looking-at message-cite-prefix-regexp))
2013                     (looking-at paragraph-start))
2014           (forward-line 1)))
2015     ;; Find the prefix
2016     (when (looking-at message-cite-prefix-regexp)
2017       (setq quoted (match-string 0))
2018       (goto-char (match-end 0))
2019       (looking-at "[ \t]*")
2020       (setq leading-space (match-string 0)))
2021     (if (and quoted
2022              (not not-break)
2023              (not bolp)
2024              (< (- point beg) (length quoted)))
2025         ;; break inside the cite prefix.
2026         (setq quoted nil
2027               end nil))
2028     (if quoted
2029         (progn
2030           (forward-line 1)
2031           (while (and (not (eobp))
2032                       (not (looking-at paragraph-separate))
2033                       (looking-at message-cite-prefix-regexp)
2034                       (equal quoted (match-string 0)))
2035             (goto-char (match-end 0))
2036             (looking-at "[ \t]*")
2037             (if (> (length leading-space) (length (match-string 0)))
2038                 (setq leading-space (match-string 0)))
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                       (looking-at message-cite-prefix-regexp)
2045                       (equal quoted (match-string 0)))
2046             (setq beg (point))
2047             (goto-char (match-end 0))
2048             (looking-at "[ \t]*")
2049             (if (> (length leading-space) (length (match-string 0)))
2050                 (setq leading-space (match-string 0)))))
2051       (while (and (not (eobp))
2052                   (not (looking-at paragraph-separate))
2053                   (not (looking-at message-cite-prefix-regexp)))
2054         (forward-line 1))
2055       (setq end (point))
2056       (goto-char beg)
2057       (while (and (if (bobp) nil (forward-line -1) t)
2058                   (not (looking-at paragraph-start))
2059                   (not (looking-at message-cite-prefix-regexp)))
2060         (setq beg (point))))
2061     (goto-char point)
2062     (save-restriction
2063       (narrow-to-region beg end)
2064       (if not-break
2065           (setq point nil)
2066         (if bolp
2067             (insert "\n")
2068           (insert "\n\n"))
2069         (setq point (point))
2070         (insert "\n\n")
2071         (delete-region (point) (re-search-forward "[ \t]*"))
2072         (when (and quoted (not bolp))
2073           (insert quoted leading-space)))
2074       (if quoted
2075           (let* ((adaptive-fill-regexp
2076                   (regexp-quote (concat quoted leading-space)))
2077                  (adaptive-fill-first-line-regexp
2078                   adaptive-fill-regexp ))
2079             (fill-paragraph arg))
2080         (fill-paragraph arg))
2081       (if point (goto-char point)))))
2082
2083 (defun message-fill-paragraph (&optional arg)
2084   "Like `fill-paragraph'."
2085   (interactive (list (if current-prefix-arg 'full)))
2086   (if (and (boundp 'filladapt-mode) filladapt-mode)
2087       nil
2088     (message-newline-and-reformat arg t)
2089     t))
2090
2091 ;; Is it better to use `mail-header-end'?
2092 (defun message-point-in-header-p ()
2093   "Return t if point is in the header."
2094   (save-excursion
2095     (let ((p (point)))
2096       (goto-char (point-min))
2097       (not (re-search-forward
2098             (concat "^" (regexp-quote mail-header-separator) "\n")
2099             p t)))))
2100
2101 (defun message-do-auto-fill ()
2102   "Like `do-auto-fill', but don't fill in message header."
2103   (unless (message-point-in-header-p)
2104     (do-auto-fill)))
2105
2106 (defun message-insert-signature (&optional force)
2107   "Insert a signature.  See documentation for variable `message-signature'."
2108   (interactive (list 0))
2109   (let* ((signature
2110           (cond
2111            ((and (null message-signature)
2112                  (eq force 0))
2113             (save-excursion
2114               (goto-char (point-max))
2115               (not (re-search-backward message-signature-separator nil t))))
2116            ((and (null message-signature)
2117                  force)
2118             t)
2119            ((message-functionp message-signature)
2120             (funcall message-signature))
2121            ((listp message-signature)
2122             (eval message-signature))
2123            (t message-signature)))
2124          (signature
2125           (cond ((stringp signature)
2126                  signature)
2127                 ((and (eq t signature)
2128                       message-signature-file
2129                       (file-exists-p message-signature-file))
2130                  signature))))
2131     (when signature
2132       (goto-char (point-max))
2133       ;; Insert the signature.
2134       (unless (bolp)
2135         (insert "\n"))
2136       (insert "\n-- \n")
2137       (if (eq signature t)
2138           (insert-file-contents message-signature-file)
2139         (insert signature))
2140       (goto-char (point-max))
2141       (or (bolp) (insert "\n")))))
2142
2143 (defun message-insert-importance-high ()
2144   "Insert header to mark message as important."
2145   (interactive)
2146   (save-excursion
2147     (message-remove-header "Importance")
2148     (message-goto-eoh)
2149     (insert "Importance: high\n")))
2150
2151 (defun message-insert-importance-low ()
2152   "Insert header to mark message as unimportant."
2153   (interactive)
2154   (save-excursion
2155     (message-remove-header "Importance")
2156     (message-goto-eoh)
2157     (insert "Importance: low\n")))
2158
2159 (defun message-insert-or-toggle-importance ()
2160   "Insert a \"Importance: high\" header, or cycle through the header values.
2161 The three allowed values according to RFC 1327 are `high', `normal'
2162 and `low'."
2163   (interactive)
2164   (save-excursion
2165     (let ((valid '("high" "normal" "low"))
2166           (new "high")
2167           cur)
2168       (when (setq cur (message-fetch-field "Importance"))
2169         (message-remove-header "Importance")
2170         (setq new (cond ((string= cur "high")
2171                          "low")
2172                         ((string= cur "low")
2173                          "normal")
2174                         (t
2175                          "high"))))
2176       (message-goto-eoh)
2177       (insert (format "Importance: %s\n" new)))))
2178
2179 (defun message-insert-disposition-notification-to ()
2180   "Request a disposition notification (return receipt) to this message.
2181 Note that this should not be used in newsgroups."
2182   (interactive)
2183   (save-excursion
2184     (message-remove-header "Disposition-Notification-To")
2185     (message-goto-eoh)
2186     (insert (format "Disposition-Notification-To: %s\n"
2187                     (or (message-fetch-field "From") (message-make-from))))))
2188
2189 (defun message-elide-region (b e)
2190   "Elide the text in the region.
2191 An ellipsis (from `message-elide-ellipsis') will be inserted where the
2192 text was killed."
2193   (interactive "r")
2194   (kill-region b e)
2195   (insert message-elide-ellipsis))
2196
2197 (defvar message-caesar-translation-table nil)
2198
2199 (defun message-caesar-region (b e &optional n)
2200   "Caesar rotate region B to E by N, default 13, for decrypting netnews."
2201   (interactive
2202    (list
2203     (min (point) (or (mark t) (point)))
2204     (max (point) (or (mark t) (point)))
2205     (when current-prefix-arg
2206       (prefix-numeric-value current-prefix-arg))))
2207
2208   (setq n (if (numberp n) (mod n 26) 13)) ;canonize N
2209   (unless (or (zerop n)                 ; no action needed for a rot of 0
2210               (= b e))                  ; no region to rotate
2211     ;; We build the table, if necessary.
2212     (when (or (not message-caesar-translation-table)
2213               (/= (aref message-caesar-translation-table ?a) (+ ?a n)))
2214       (setq message-caesar-translation-table
2215             (message-make-caesar-translation-table n)))
2216     (translate-region b e message-caesar-translation-table)))
2217
2218 (defun message-make-caesar-translation-table (n)
2219   "Create a rot table with offset N."
2220   (let ((i -1)
2221         (table (make-string 256 0)))
2222     (while (< (incf i) 256)
2223       (aset table i i))
2224     (concat
2225      (substring table 0 ?A)
2226      (substring table (+ ?A n) (+ ?A n (- 26 n)))
2227      (substring table ?A (+ ?A n))
2228      (substring table (+ ?A 26) ?a)
2229      (substring table (+ ?a n) (+ ?a n (- 26 n)))
2230      (substring table ?a (+ ?a n))
2231      (substring table (+ ?a 26) 255))))
2232
2233 (defun message-caesar-buffer-body (&optional rotnum)
2234   "Caesar rotate all letters in the current buffer by 13 places.
2235 Used to encode/decode possibly offensive messages (commonly in rec.humor).
2236 With prefix arg, specifies the number of places to rotate each letter forward.
2237 Mail and USENET news headers are not rotated."
2238   (interactive (if current-prefix-arg
2239                    (list (prefix-numeric-value current-prefix-arg))
2240                  (list nil)))
2241   (save-excursion
2242     (save-restriction
2243       (when (message-goto-body)
2244         (narrow-to-region (point) (point-max)))
2245       (message-caesar-region (point-min) (point-max) rotnum))))
2246
2247 (defun message-pipe-buffer-body (program)
2248   "Pipe the message body in the current buffer through PROGRAM."
2249   (save-excursion
2250     (save-restriction
2251       (when (message-goto-body)
2252         (narrow-to-region (point) (point-max)))
2253       (shell-command-on-region
2254        (point-min) (point-max) program nil t))))
2255
2256 (defun message-rename-buffer (&optional enter-string)
2257   "Rename the *message* buffer to \"*message* RECIPIENT\".
2258 If the function is run with a prefix, it will ask for a new buffer
2259 name, rather than giving an automatic name."
2260   (interactive "Pbuffer name: ")
2261   (save-excursion
2262     (save-restriction
2263       (goto-char (point-min))
2264       (narrow-to-region (point)
2265                         (search-forward mail-header-separator nil 'end))
2266       (let* ((mail-to (or
2267                        (if (message-news-p) (message-fetch-field "Newsgroups")
2268                          (message-fetch-field "To"))
2269                        ""))
2270              (mail-trimmed-to
2271               (if (string-match "," mail-to)
2272                   (concat (substring mail-to 0 (match-beginning 0)) ", ...")
2273                 mail-to))
2274              (name-default (concat "*message* " mail-trimmed-to))
2275              (name (if enter-string
2276                        (read-string "New buffer name: " name-default)
2277                      name-default)))
2278         (rename-buffer name t)))))
2279
2280 (defun message-fill-yanked-message (&optional justifyp)
2281   "Fill the paragraphs of a message yanked into this one.
2282 Numeric argument means justify as well."
2283   (interactive "P")
2284   (save-excursion
2285     (goto-char (point-min))
2286     (search-forward (concat "\n" mail-header-separator "\n") nil t)
2287     (let ((fill-prefix message-yank-prefix))
2288       (fill-individual-paragraphs (point) (point-max) justifyp))))
2289
2290 (defun message-indent-citation ()
2291   "Modify text just inserted from a message to be cited.
2292 The inserted text should be the region.
2293 When this function returns, the region is again around the modified text.
2294
2295 Normally, indent each nonblank line `message-indentation-spaces' spaces.
2296 However, if `message-yank-prefix' is non-nil, insert that prefix on each line."
2297   (let ((start (point)))
2298     ;; Remove unwanted headers.
2299     (when message-ignored-cited-headers
2300       (let (all-removed)
2301         (save-restriction
2302           (narrow-to-region
2303            (goto-char start)
2304            (if (search-forward "\n\n" nil t)
2305                (1- (point))
2306              (point)))
2307           (message-remove-header message-ignored-cited-headers t)
2308           (when (= (point-min) (point-max))
2309             (setq all-removed t))
2310           (goto-char (point-max)))
2311         (if all-removed
2312             (goto-char start)
2313           (forward-line 1))))
2314     ;; Delete blank lines at the start of the buffer.
2315     (while (and (point-min)
2316                 (eolp)
2317                 (not (eobp)))
2318       (message-delete-line))
2319     ;; Delete blank lines at the end of the buffer.
2320     (goto-char (point-max))
2321     (unless (eolp)
2322       (insert "\n"))
2323     (while (and (zerop (forward-line -1))
2324                 (looking-at "$"))
2325       (message-delete-line))
2326     ;; Do the indentation.
2327     (if (null message-yank-prefix)
2328         (indent-rigidly start (mark t) message-indentation-spaces)
2329       (save-excursion
2330         (goto-char start)
2331         (while (< (point) (mark t))
2332           (if (or (looking-at ">") (looking-at "^$"))
2333               (insert message-yank-cited-prefix)
2334             (insert message-yank-prefix))
2335           (forward-line 1))))
2336     (goto-char start)))
2337
2338 (defun message-yank-original (&optional arg)
2339   "Insert the message being replied to, if any.
2340 Puts point before the text and mark after.
2341 Normally indents each nonblank line ARG spaces (default 3).  However,
2342 if `message-yank-prefix' is non-nil, insert that prefix on each line.
2343
2344 This function uses `message-cite-function' to do the actual citing.
2345
2346 Just \\[universal-argument] as argument means don't indent, insert no
2347 prefix, and don't delete any headers."
2348   (interactive "P")
2349   (let ((modified (buffer-modified-p)))
2350     (when (and message-reply-buffer
2351                message-cite-function)
2352       (delete-windows-on message-reply-buffer t)
2353       (insert-buffer message-reply-buffer)
2354       (unless arg
2355         (funcall message-cite-function))
2356       (message-exchange-point-and-mark)
2357       (unless (bolp)
2358         (insert ?\n))
2359       (unless modified
2360         (setq message-checksum (message-checksum))))))
2361
2362 (defun message-yank-buffer (buffer)
2363   "Insert BUFFER into the current buffer and quote it."
2364   (interactive "bYank buffer: ")
2365   (let ((message-reply-buffer buffer))
2366     (save-window-excursion
2367       (message-yank-original))))
2368
2369 (defun message-buffers ()
2370   "Return a list of active message buffers."
2371   (let (buffers)
2372     (save-excursion
2373       (dolist (buffer (buffer-list t))
2374         (set-buffer buffer)
2375         (when (and (eq major-mode 'message-mode)
2376                    (null message-sent-message-via))
2377           (push (buffer-name buffer) buffers))))
2378     (nreverse buffers)))
2379
2380 (defun message-cite-original-without-signature ()
2381   "Cite function in the standard Message manner."
2382   (let ((start (point))
2383         (end (mark t))
2384         (functions
2385          (when message-indent-citation-function
2386            (if (listp message-indent-citation-function)
2387                message-indent-citation-function
2388              (list message-indent-citation-function)))))
2389     (mml-quote-region start end)
2390     ;; Allow undoing.
2391     (undo-boundary)
2392     (goto-char end)
2393     (when (re-search-backward message-signature-separator start t)
2394       ;; Also peel off any blank lines before the signature.
2395       (forward-line -1)
2396       (while (looking-at "^[ \t]*$")
2397         (forward-line -1))
2398       (forward-line 1)
2399       (delete-region (point) end)
2400       (unless (search-backward "\n\n" start t)
2401         ;; Insert a blank line if it is peeled off.
2402         (insert "\n")))
2403     (goto-char start)
2404     (while functions
2405       (funcall (pop functions)))
2406     (when message-citation-line-function
2407       (unless (bolp)
2408         (insert "\n"))
2409       (funcall message-citation-line-function))))
2410
2411 (eval-when-compile (defvar mail-citation-hook)) ;Compiler directive
2412 (defun message-cite-original ()
2413   "Cite function in the standard Message manner."
2414   (if (and (boundp 'mail-citation-hook)
2415            mail-citation-hook)
2416       (run-hooks 'mail-citation-hook)
2417     (let ((start (point))
2418           (end (mark t))
2419           (functions
2420            (when message-indent-citation-function
2421              (if (listp message-indent-citation-function)
2422                  message-indent-citation-function
2423                (list message-indent-citation-function)))))
2424       (mml-quote-region start end)
2425       (goto-char start)
2426       (while functions
2427         (funcall (pop functions)))
2428       (when message-citation-line-function
2429         (unless (bolp)
2430           (insert "\n"))
2431         (funcall message-citation-line-function)))))
2432
2433 (defun message-insert-citation-line ()
2434   "Insert a simple citation line."
2435   (when message-reply-headers
2436     (insert (mail-header-from message-reply-headers) " writes:\n\n")))
2437
2438 (defun message-position-on-field (header &rest afters)
2439   (let ((case-fold-search t))
2440     (save-restriction
2441       (narrow-to-region
2442        (goto-char (point-min))
2443        (progn
2444          (re-search-forward
2445           (concat "^" (regexp-quote mail-header-separator) "$"))
2446          (match-beginning 0)))
2447       (goto-char (point-min))
2448       (if (re-search-forward (concat "^" (regexp-quote header) ":") nil t)
2449           (progn
2450             (re-search-forward "^[^ \t]" nil 'move)
2451             (beginning-of-line)
2452             (skip-chars-backward "\n")
2453             t)
2454         (while (and afters
2455                     (not (re-search-forward
2456                           (concat "^" (regexp-quote (car afters)) ":")
2457                           nil t)))
2458           (pop afters))
2459         (when afters
2460           (re-search-forward "^[^ \t]" nil 'move)
2461           (beginning-of-line))
2462         (insert header ": \n")
2463         (forward-char -1)
2464         nil))))
2465
2466 (defun message-remove-signature ()
2467   "Remove the signature from the text between point and mark.
2468 The text will also be indented the normal way."
2469   (save-excursion
2470     (let ((start (point))
2471           mark)
2472       (if (not (re-search-forward message-signature-separator (mark t) t))
2473           ;; No signature here, so we just indent the cited text.
2474           (message-indent-citation)
2475         ;; Find the last non-empty line.
2476         (forward-line -1)
2477         (while (looking-at "[ \t]*$")
2478           (forward-line -1))
2479         (forward-line 1)
2480         (setq mark (set-marker (make-marker) (point)))
2481         (goto-char start)
2482         (message-indent-citation)
2483         ;; Enable undoing the deletion.
2484         (undo-boundary)
2485         (delete-region mark (mark t))
2486         (set-marker mark nil)))))
2487
2488 \f
2489
2490 ;;;
2491 ;;; Sending messages
2492 ;;;
2493
2494 (defun message-send-and-exit (&optional arg)
2495   "Send message like `message-send', then, if no errors, exit from mail buffer."
2496   (interactive "P")
2497   (let ((buf (current-buffer))
2498         (actions message-exit-actions))
2499     (when (and (message-send arg)
2500                (buffer-name buf))
2501       (if message-kill-buffer-on-exit
2502           (kill-buffer buf)
2503         (bury-buffer buf)
2504         (when (eq buf (current-buffer))
2505           (message-bury buf)))
2506       (message-do-actions actions)
2507       t)))
2508
2509 (defun message-dont-send ()
2510   "Don't send the message you have been editing."
2511   (interactive)
2512   (set-buffer-modified-p t)
2513   (save-buffer)
2514   (let ((actions message-postpone-actions))
2515     (message-bury (current-buffer))
2516     (message-do-actions actions)))
2517
2518 (defun message-kill-buffer ()
2519   "Kill the current buffer."
2520   (interactive)
2521   (when (or (not (buffer-modified-p))
2522             (yes-or-no-p "Message modified; kill anyway? "))
2523     (let ((actions message-kill-actions)
2524           (draft-article message-draft-article)
2525           (auto-save-file-name buffer-auto-save-file-name)
2526           (file-name buffer-file-name)
2527           (modified (buffer-modified-p)))
2528       (setq buffer-file-name nil)
2529       (kill-buffer (current-buffer))
2530       (when (and (or (and auto-save-file-name
2531                           (file-exists-p auto-save-file-name))
2532                      (and file-name
2533                           (file-exists-p file-name)))
2534                (yes-or-no-p (format "Remove the backup file%s? "
2535                                     (if modified " too" ""))))
2536         (ignore-errors
2537           (delete-file auto-save-file-name))
2538         (let ((message-draft-article draft-article))
2539           (message-disassociate-draft)))
2540       (message-do-actions actions))))
2541
2542 (defun message-bury (buffer)
2543   "Bury this mail BUFFER."
2544   (let ((newbuf (other-buffer buffer)))
2545     (bury-buffer buffer)
2546     (if (and (fboundp 'frame-parameters)
2547              (cdr (assq 'dedicated (frame-parameters)))
2548              (not (null (delq (selected-frame) (visible-frame-list)))))
2549         (delete-frame (selected-frame))
2550       (switch-to-buffer newbuf))))
2551
2552 (defun message-send (&optional arg)
2553   "Send the message in the current buffer.
2554 If `message-interactive' is non-nil, wait for success indication or
2555 error messages, and inform user.
2556 Otherwise any failure is reported in a message back to the user from
2557 the mailer.
2558 The usage of ARG is defined by the instance that called Message.
2559 It should typically alter the sending method in some way or other."
2560   (interactive "P")
2561   ;; Make it possible to undo the coming changes.
2562   (undo-boundary)
2563   (let ((inhibit-read-only t))
2564     (put-text-property (point-min) (point-max) 'read-only nil))
2565   (message-fix-before-sending)
2566   (run-hooks 'message-send-hook)
2567   (message message-sending-message)
2568   (let ((alist message-send-method-alist)
2569         (success t)
2570         elem sent dont-barf-on-no-method
2571         (message-options message-options))
2572     (message-options-set-recipient)
2573     (while (and success
2574                 (setq elem (pop alist)))
2575       (when (funcall (cadr elem))
2576         (when (and (or (not (memq (car elem)
2577                                   message-sent-message-via))
2578                        (if (or (message-gnksa-enable-p 'multiple-copies)
2579                                (not (eq (car elem) 'news)))
2580                            (y-or-n-p
2581                             (format
2582                              "Already sent message via %s; resend? "
2583                              (car elem)))
2584                          (error "Denied posting -- multiple copies")))
2585                    (setq success (funcall (caddr elem) arg)))
2586           (setq sent t))))
2587     (unless (or sent
2588                 (not success)
2589                 (let ((fcc (message-fetch-field "Fcc"))
2590                       (gcc (message-fetch-field "Gcc")))
2591                   (when (or fcc gcc)
2592                     (or (eq message-allow-no-recipients 'always)
2593                         (and (not (eq message-allow-no-recipients 'never))
2594                              (setq dont-barf-on-no-method
2595                                    (gnus-y-or-n-p
2596                                     (format "No receiver, perform %s anyway? "
2597                                             (cond ((and fcc gcc) "Fcc and Gcc")
2598                                                   (fcc "Fcc")
2599                                                   (t "Gcc"))))))))))
2600       (error "No methods specified to send by"))
2601     (when (or dont-barf-on-no-method
2602               (and success sent))
2603       (message-do-fcc)
2604       (save-excursion
2605         (run-hooks 'message-sent-hook))
2606       (message "Sending...done")
2607       ;; Mark the buffer as unmodified and delete auto-save.
2608       (set-buffer-modified-p nil)
2609       (delete-auto-save-file-if-necessary t)
2610       (message-disassociate-draft)
2611       ;; Delete other mail buffers and stuff.
2612       (message-do-send-housekeeping)
2613       (message-do-actions message-send-actions)
2614       ;; Return success.
2615       t)))
2616
2617 (defun message-send-via-mail (arg)
2618   "Send the current message via mail."
2619   (message-send-mail arg))
2620
2621 (defun message-send-via-news (arg)
2622   "Send the current message via news."
2623   (funcall message-send-news-function arg))
2624
2625 (defmacro message-check (type &rest forms)
2626   "Eval FORMS if TYPE is to be checked."
2627   `(or (message-check-element ,type)
2628        (save-excursion
2629          ,@forms)))
2630
2631 (put 'message-check 'lisp-indent-function 1)
2632 (put 'message-check 'edebug-form-spec '(form body))
2633
2634 (defun message-text-with-property (prop)
2635   "Return a list of all points where the text has PROP."
2636   (let ((points nil)
2637         (point (point-min)))
2638     (save-excursion
2639       (while (< point (point-max))
2640         (when (get-text-property point prop)
2641           (push point points))
2642         (incf point)))
2643     (nreverse points)))
2644
2645 (defun message-fix-before-sending ()
2646   "Do various things to make the message nice before sending it."
2647   ;; Make sure there's a newline at the end of the message.
2648   (goto-char (point-max))
2649   (unless (bolp)
2650     (insert "\n"))
2651   ;; Delete all invisible text.
2652   (message-check 'invisible-text
2653     (let ((points (message-text-with-property 'invisible)))
2654       (when points
2655         (goto-char (car points))
2656         (dolist (point points)
2657           (add-text-properties point (1+ point)
2658                                '(invisible nil highlight t)))
2659         (unless (yes-or-no-p
2660                  "Invisible text found and made visible; continue posting? ")
2661           (error "Invisible text found and made visible"))))))
2662
2663 (defun message-add-action (action &rest types)
2664   "Add ACTION to be performed when doing an exit of type TYPES."
2665   (let (var)
2666     (while types
2667       (set (setq var (intern (format "message-%s-actions" (pop types))))
2668            (nconc (symbol-value var) (list action))))))
2669
2670 (defun message-do-actions (actions)
2671   "Perform all actions in ACTIONS."
2672   ;; Now perform actions on successful sending.
2673   (while actions
2674     (ignore-errors
2675       (cond
2676        ;; A simple function.
2677        ((message-functionp (car actions))
2678         (funcall (car actions)))
2679        ;; Something to be evaled.
2680        (t
2681         (eval (car actions)))))
2682     (pop actions)))
2683
2684 (defun message-send-mail-partially ()
2685   "Send mail as message/partial."
2686   ;; replace the header delimiter with a blank line
2687   (goto-char (point-min))
2688   (re-search-forward
2689    (concat "^" (regexp-quote mail-header-separator) "\n"))
2690   (replace-match "\n")
2691   (run-hooks 'message-send-mail-hook)
2692   (let ((p (goto-char (point-min)))
2693         (tembuf (message-generate-new-buffer-clone-locals " message temp"))
2694         (curbuf (current-buffer))
2695         (id (message-make-message-id)) (n 1)
2696         plist total  header required-mail-headers)
2697     (while (not (eobp))
2698       (if (< (point-max) (+ p message-send-mail-partially-limit))
2699           (goto-char (point-max))
2700         (goto-char (+ p message-send-mail-partially-limit))
2701         (beginning-of-line)
2702         (if (<= (point) p) (forward-line 1))) ;; In case of bad message.
2703       (push p plist)
2704       (setq p (point)))
2705     (setq total (length plist))
2706     (push (point-max) plist)
2707     (setq plist (nreverse plist))
2708     (unwind-protect
2709         (save-excursion
2710           (setq p (pop plist))
2711           (while plist
2712             (set-buffer curbuf)
2713             (copy-to-buffer tembuf p (car plist))
2714             (set-buffer tembuf)
2715             (goto-char (point-min))
2716             (if header
2717                 (progn
2718                   (goto-char (point-min))
2719                   (narrow-to-region (point) (point))
2720                   (insert header))
2721               (message-goto-eoh)
2722               (setq header (buffer-substring (point-min) (point)))
2723               (goto-char (point-min))
2724               (narrow-to-region (point) (point))
2725               (insert header)
2726               (message-remove-header "Mime-Version")
2727               (message-remove-header "Content-Type")
2728               (message-remove-header "Content-Transfer-Encoding")
2729               (message-remove-header "Message-ID")
2730               (message-remove-header "Lines")
2731               (goto-char (point-max))
2732               (insert "Mime-Version: 1.0\n")
2733               (setq header (buffer-substring (point-min) (point-max))))
2734             (goto-char (point-max))
2735             (insert (format "Content-Type: message/partial; id=\"%s\"; number=%d; total=%d\n\n"
2736                             id n total))
2737             (forward-char -1)
2738             (let ((mail-header-separator ""))
2739               (when (memq 'Message-ID message-required-mail-headers)
2740                 (insert "Message-ID: " (message-make-message-id) "\n"))
2741               (when (memq 'Lines message-required-mail-headers)
2742                 (insert "Lines: " (message-make-lines) "\n"))
2743               (message-goto-subject)
2744               (end-of-line)
2745               (insert (format " (%d/%d)" n total))
2746               (widen)
2747               (mm-with-unibyte-current-buffer
2748                 (funcall (or message-send-mail-real-function
2749                              message-send-mail-function))))
2750             (setq n (+ n 1))
2751             (setq p (pop plist))
2752             (erase-buffer)))
2753       (kill-buffer tembuf))))
2754
2755 (defun message-send-mail (&optional arg)
2756   (require 'mail-utils)
2757   (let* ((tembuf (message-generate-new-buffer-clone-locals " message temp"))
2758          (case-fold-search nil)
2759          (news (message-news-p))
2760          (mailbuf (current-buffer))
2761          (message-this-is-mail t)
2762          (message-posting-charset
2763           (if (fboundp 'gnus-setup-posting-charset)
2764               (gnus-setup-posting-charset nil)
2765             message-posting-charset))
2766          (headers message-required-mail-headers))
2767     (save-restriction
2768       (message-narrow-to-headers)
2769       ;; Generate the Mail-Followup-To header if the header is not there...
2770       (if (and (or message-subscribed-regexps
2771                    message-subscribed-addresses
2772                    message-subscribed-address-file
2773                    message-subscribed-address-functions)
2774                (not (mail-fetch-field "mail-followup-to")))
2775           (setq headers
2776                 (cons
2777                  (cons "Mail-Followup-To" (message-make-mft))
2778                  message-required-mail-headers))
2779         ;; otherwise, delete the MFT header if the field is empty
2780         (when (equal "" (mail-fetch-field "mail-followup-to"))
2781           (message-remove-header "^Mail-Followup-To:")))
2782       ;; Insert some headers.
2783       (let ((message-deletable-headers
2784              (if news nil message-deletable-headers)))
2785         (message-generate-headers headers))
2786       ;; Let the user do all of the above.
2787       (run-hooks 'message-header-hook))
2788     (unwind-protect
2789         (save-excursion
2790           (set-buffer tembuf)
2791           (erase-buffer)
2792           ;; Avoid copying text props (except hard newlines).
2793           (insert (with-current-buffer mailbuf
2794                     (mml-buffer-substring-no-properties-except-hard-newlines
2795                      (point-min) (point-max))))
2796           ;; Remove some headers.
2797           (message-encode-message-body)
2798           (save-restriction
2799             (message-narrow-to-headers)
2800             ;; We (re)generate the Lines header.
2801             (when (memq 'Lines message-required-mail-headers)
2802               (message-generate-headers '(Lines)))
2803             ;; Remove some headers.
2804             (message-remove-header message-ignored-mail-headers t)
2805             (let ((mail-parse-charset message-default-charset))
2806               (mail-encode-encoded-word-buffer)))
2807           (goto-char (point-max))
2808           ;; require one newline at the end.
2809           (or (= (preceding-char) ?\n)
2810               (insert ?\n))
2811           (when
2812               (save-restriction
2813                 (message-narrow-to-headers)
2814                 (and news
2815                      (or (message-fetch-field "cc")
2816                          (message-fetch-field "to"))
2817                      (let ((content-type (message-fetch-field "content-type")))
2818                        (or
2819                         (not content-type)
2820                         (string= "text/plain"
2821                                  (car
2822                                   (mail-header-parse-content-type
2823                                    content-type)))))))
2824             (message-insert-courtesy-copy))
2825           (if (or (not message-send-mail-partially-limit)
2826                   (< (point-max) message-send-mail-partially-limit)
2827                   (not (y-or-n-p "Message exceeds message-send-mail-partially-limit, send in parts? ")))
2828               (mm-with-unibyte-current-buffer
2829                 (message "Sending via mail...")
2830                 (funcall (or message-send-mail-real-function
2831                              message-send-mail-function)))
2832             (message-send-mail-partially)))
2833       (kill-buffer tembuf))
2834     (set-buffer mailbuf)
2835     (push 'mail message-sent-message-via)))
2836
2837 (defun message-send-mail-with-sendmail ()
2838   "Send off the prepared buffer with sendmail."
2839   (let ((errbuf (if message-interactive
2840                     (message-generate-new-buffer-clone-locals
2841                      " sendmail errors")
2842                   0))
2843         resend-to-addresses delimline)
2844     (let ((case-fold-search t))
2845       (save-restriction
2846         (message-narrow-to-headers)
2847         (setq resend-to-addresses (message-fetch-field "resent-to")))
2848       ;; Change header-delimiter to be what sendmail expects.
2849       (goto-char (point-min))
2850       (re-search-forward
2851        (concat "^" (regexp-quote mail-header-separator) "\n"))
2852       (replace-match "\n")
2853       (backward-char 1)
2854       (setq delimline (point-marker))
2855       (run-hooks 'message-send-mail-hook)
2856       ;; Insert an extra newline if we need it to work around
2857       ;; Sun's bug that swallows newlines.
2858       (goto-char (1+ delimline))
2859       (when (eval message-mailer-swallows-blank-line)
2860         (newline))
2861       (when message-interactive
2862         (save-excursion
2863           (set-buffer errbuf)
2864           (erase-buffer))))
2865     (let ((default-directory "/")
2866           (coding-system-for-write message-send-coding-system))
2867       (apply 'call-process-region
2868              (append (list (point-min) (point-max)
2869                            (if (boundp 'sendmail-program)
2870                                sendmail-program
2871                              "/usr/lib/sendmail")
2872                            nil errbuf nil "-oi")
2873                      ;; Always specify who from,
2874                      ;; since some systems have broken sendmails.
2875                      ;; But some systems are more broken with -f, so
2876                      ;; we'll let users override this.
2877                      (if (null message-sendmail-f-is-evil)
2878                          (list "-f" (message-make-address)))
2879                      ;; These mean "report errors by mail"
2880                      ;; and "deliver in background".
2881                      (if (null message-interactive) '("-oem" "-odb"))
2882                      ;; Get the addresses from the message
2883                      ;; unless this is a resend.
2884                      ;; We must not do that for a resend
2885                      ;; because we would find the original addresses.
2886                      ;; For a resend, include the specific addresses.
2887                      (if resend-to-addresses
2888                          (list resend-to-addresses)
2889                        '("-t")))))
2890     (when message-interactive
2891       (save-excursion
2892         (set-buffer errbuf)
2893         (goto-char (point-min))
2894         (while (re-search-forward "\n\n* *" nil t)
2895           (replace-match "; "))
2896         (if (not (zerop (buffer-size)))
2897             (error "Sending...failed to %s"
2898                    (buffer-substring (point-min) (point-max)))))
2899       (when (bufferp errbuf)
2900         (kill-buffer errbuf)))))
2901
2902 (defun message-send-mail-with-qmail ()
2903   "Pass the prepared message buffer to qmail-inject.
2904 Refer to the documentation for the variable `message-send-mail-function'
2905 to find out how to use this."
2906   ;; replace the header delimiter with a blank line
2907   (goto-char (point-min))
2908   (re-search-forward
2909    (concat "^" (regexp-quote mail-header-separator) "\n"))
2910   (replace-match "\n")
2911   (run-hooks 'message-send-mail-hook)
2912   ;; send the message
2913   (case
2914       (let ((coding-system-for-write message-send-coding-system))
2915         (apply
2916          'call-process-region 1 (point-max) message-qmail-inject-program
2917          nil nil nil
2918          ;; qmail-inject's default behaviour is to look for addresses on the
2919          ;; command line; if there're none, it scans the headers.
2920          ;; yes, it does The Right Thing w.r.t. Resent-To and it's kin.
2921          ;;
2922          ;; in general, ALL of qmail-inject's defaults are perfect for simply
2923          ;; reading a formatted (i. e., at least a To: or Resent-To header)
2924          ;; message from stdin.
2925          ;;
2926          ;; qmail also has the advantage of not having been raped by
2927          ;; various vendors, so we don't have to allow for that, either --
2928          ;; compare this with message-send-mail-with-sendmail and weep
2929          ;; for sendmail's lost innocence.
2930          ;;
2931          ;; all this is way cool coz it lets us keep the arguments entirely
2932          ;; free for -inject-arguments -- a big win for the user and for us
2933          ;; since we don't have to play that double-guessing game and the user
2934          ;; gets full control (no gestapo'ish -f's, for instance).  --sj
2935          message-qmail-inject-args))
2936     ;; qmail-inject doesn't say anything on it's stdout/stderr,
2937     ;; we have to look at the retval instead
2938     (0 nil)
2939     (100 (error "qmail-inject reported permanent failure"))
2940     (111 (error "qmail-inject reported transient failure"))
2941     ;; should never happen
2942     (t   (error "qmail-inject reported unknown failure"))))
2943
2944 (defun message-send-mail-with-mh ()
2945   "Send the prepared message buffer with mh."
2946   (let ((mh-previous-window-config nil)
2947         (name (mh-new-draft-name)))
2948     (setq buffer-file-name name)
2949     ;; MH wants to generate these headers itself.
2950     (when message-mh-deletable-headers
2951       (let ((headers message-mh-deletable-headers))
2952         (while headers
2953           (goto-char (point-min))
2954           (and (re-search-forward
2955                 (concat "^" (symbol-name (car headers)) ": *") nil t)
2956                (message-delete-line))
2957           (pop headers))))
2958     (run-hooks 'message-send-mail-hook)
2959     ;; Pass it on to mh.
2960     (mh-send-letter)))
2961
2962 (defun message-canlock-generate ()
2963   "Return a string that is non-trival to guess.
2964 Do not use this for anything important, it is cryptographically weak."
2965   (sha1 (concat (message-unique-id)
2966                 (format "%x%x%x" (random) (random t) (random))
2967                 (prin1-to-string (recent-keys))
2968                 (prin1-to-string (garbage-collect)))))
2969
2970 (defun message-canlock-password ()
2971   "The password used by message for cancel locks.
2972 This is the value of `canlock-password', if that option is non-nil.
2973 Otherwise, generate and save a value for `canlock-password' first."
2974   (unless canlock-password
2975     (customize-save-variable 'canlock-password (message-canlock-generate)))
2976   canlock-password)
2977
2978 (defun message-insert-canlock ()
2979   (when message-insert-canlock
2980     (message-canlock-password)
2981     (canlock-insert-header)))
2982
2983 (defun message-send-news (&optional arg)
2984   (let* ((tembuf (message-generate-new-buffer-clone-locals " *message temp*"))
2985          (case-fold-search nil)
2986          (method (if (message-functionp message-post-method)
2987                      (funcall message-post-method arg)
2988                    message-post-method))
2989          (newsgroups-field (save-restriction
2990                             (message-narrow-to-headers-or-head)
2991                             (message-fetch-field "Newsgroups")))
2992          (followup-field (save-restriction
2993                            (message-narrow-to-headers-or-head)
2994                            (message-fetch-field "Followup-To")))
2995          ;; BUG: We really need to get the charset for each name in the
2996          ;; Newsgroups and Followup-To lines to allow crossposting
2997          ;; between group namess with incompatible character sets.
2998          ;; -- Per Abrahamsen <abraham@dina.kvl.dk> 2001-10-08.
2999          (group-field-charset
3000           (gnus-group-name-charset method newsgroups-field))
3001          (followup-field-charset 
3002           (gnus-group-name-charset method (or followup-field "")))
3003          (rfc2047-header-encoding-alist
3004           (append (when group-field-charset
3005                     (list (cons "Newsgroups" group-field-charset)))
3006                   (when followup-field-charset
3007                     (list (cons "Followup-To" followup-field-charset)))
3008                   rfc2047-header-encoding-alist))
3009          (messbuf (current-buffer))
3010          (message-syntax-checks
3011           (if (and arg
3012                    (listp message-syntax-checks))
3013               (cons '(existing-newsgroups . disabled)
3014                     message-syntax-checks)
3015             message-syntax-checks))
3016          (message-this-is-news t)
3017          (message-posting-charset
3018           (gnus-setup-posting-charset newsgroups-field))
3019          result)
3020     (if (not (message-check-news-body-syntax))
3021         nil
3022       (save-restriction
3023         (message-narrow-to-headers)
3024         ;; Insert some headers.
3025         (message-generate-headers message-required-news-headers)
3026         (message-insert-canlock)
3027         ;; Let the user do all of the above.
3028         (run-hooks 'message-header-hook))
3029       ;; Note: This check will be disabled by the ".*" default value for
3030       ;; gnus-group-name-charset-group-alist. -- Pa 2001-10-07.
3031       (when (and group-field-charset
3032                  (listp message-syntax-checks))
3033         (setq message-syntax-checks
3034               (cons '(valid-newsgroups . disabled)
3035                     message-syntax-checks)))
3036       (message-cleanup-headers)
3037       (if (not (let ((message-post-method method))
3038                  (message-check-news-syntax)))
3039           nil
3040         (unwind-protect
3041             (save-excursion
3042               (set-buffer tembuf)
3043               (buffer-disable-undo)
3044               (erase-buffer)
3045               ;; Avoid copying text props (except hard newlines).
3046               (insert
3047                (with-current-buffer messbuf
3048                  (mml-buffer-substring-no-properties-except-hard-newlines
3049                   (point-min) (point-max))))
3050               (message-encode-message-body)
3051               ;; Remove some headers.
3052               (save-restriction
3053                 (message-narrow-to-headers)
3054                 ;; We (re)generate the Lines header.
3055                 (when (memq 'Lines message-required-mail-headers)
3056                   (message-generate-headers '(Lines)))
3057                 ;; Remove some headers.
3058                 (message-remove-header message-ignored-news-headers t)
3059                 (let ((mail-parse-charset message-default-charset))
3060                   (mail-encode-encoded-word-buffer)))
3061               (goto-char (point-max))
3062               ;; require one newline at the end.
3063               (or (= (preceding-char) ?\n)
3064                   (insert ?\n))
3065               (let ((case-fold-search t))
3066                 ;; Remove the delimiter.
3067                 (goto-char (point-min))
3068                 (re-search-forward
3069                  (concat "^" (regexp-quote mail-header-separator) "\n"))
3070                 (replace-match "\n")
3071                 (backward-char 1))
3072               (run-hooks 'message-send-news-hook)
3073               (gnus-open-server method)
3074               (message "Sending news with %s..." (gnus-server-string method))
3075               (setq result (let ((mail-header-separator ""))
3076                              (gnus-request-post method))))
3077           (kill-buffer tembuf))
3078         (set-buffer messbuf)
3079         (if result
3080             (push 'news message-sent-message-via)
3081           (message "Couldn't send message via news: %s"
3082                    (nnheader-get-report (car method)))
3083           nil)))))
3084
3085 ;;;
3086 ;;; Header generation & syntax checking.
3087 ;;;
3088
3089 (defun message-check-element (type)
3090   "Return non-nil if this TYPE is not to be checked."
3091   (if (eq message-syntax-checks 'dont-check-for-anything-just-trust-me)
3092       t
3093     (let ((able (assq type message-syntax-checks)))
3094       (and (consp able)
3095            (eq (cdr able) 'disabled)))))
3096
3097 (defun message-check-news-syntax ()
3098   "Check the syntax of the message."
3099   (save-excursion
3100     (save-restriction
3101       (widen)
3102       ;; We narrow to the headers and check them first.
3103       (save-excursion
3104         (save-restriction
3105           (message-narrow-to-headers)
3106           (message-check-news-header-syntax))))))
3107
3108 (defun message-check-news-header-syntax ()
3109   (and
3110    ;; Check Newsgroups header.
3111    (message-check 'newsgroups
3112      (let ((group (message-fetch-field "newsgroups")))
3113        (or
3114         (and group
3115              (not (string-match "\\`[ \t]*\\'" group)))
3116         (ignore
3117          (message
3118           "The newsgroups field is empty or missing.  Posting is denied.")))))
3119    ;; Check the Subject header.
3120    (message-check 'subject
3121      (let* ((case-fold-search t)
3122             (subject (message-fetch-field "subject")))
3123        (or
3124         (and subject
3125              (not (string-match "\\`[ \t]*\\'" subject)))
3126         (ignore
3127          (message
3128           "The subject field is empty or missing.  Posting is denied.")))))
3129    ;; Check for commands in Subject.
3130    (message-check 'subject-cmsg
3131      (if (string-match "^cmsg " (message-fetch-field "subject"))
3132          (y-or-n-p
3133           "The control code \"cmsg\" is in the subject.  Really post? ")
3134        t))
3135    ;; Check for multiple identical headers.
3136    (message-check 'multiple-headers
3137      (let (found)
3138        (while (and (not found)
3139                    (re-search-forward "^[^ \t:]+: " nil t))
3140          (save-excursion
3141            (or (re-search-forward
3142                 (concat "^"
3143                         (regexp-quote
3144                          (setq found
3145                                (buffer-substring
3146                                 (match-beginning 0) (- (match-end 0) 2))))
3147                         ":")
3148                 nil t)
3149                (setq found nil))))
3150        (if found
3151            (y-or-n-p (format "Multiple %s headers.  Really post? " found))
3152          t)))
3153    ;; Check for Version and Sendsys.
3154    (message-check 'sendsys
3155      (if (re-search-forward "^Sendsys:\\|^Version:" nil t)
3156          (y-or-n-p
3157           (format "The article contains a %s command.  Really post? "
3158                   (buffer-substring (match-beginning 0)
3159                                     (1- (match-end 0)))))
3160        t))
3161    ;; See whether we can shorten Followup-To.
3162    (message-check 'shorten-followup-to
3163      (let ((newsgroups (message-fetch-field "newsgroups"))
3164            (followup-to (message-fetch-field "followup-to"))
3165            to)
3166        (when (and newsgroups
3167                   (string-match "," newsgroups)
3168                   (not followup-to)
3169                   (not
3170                    (zerop
3171                     (length
3172                      (setq to (completing-read
3173                                "Followups to: (default all groups) "
3174                                (mapcar (lambda (g) (list g))
3175                                        (cons "poster"
3176                                              (message-tokenize-header
3177                                               newsgroups)))))))))
3178          (goto-char (point-min))
3179          (insert "Followup-To: " to "\n"))
3180        t))
3181    ;; Check "Shoot me".
3182    (message-check 'shoot
3183      (if (re-search-forward
3184           "Message-ID.*.i-did-not-set--mail-host-address--so-shoot-me" nil t)
3185          (y-or-n-p "You appear to have a misconfigured system.  Really post? ")
3186        t))
3187    ;; Check for Approved.
3188    (message-check 'approved
3189      (if (re-search-forward "^Approved:" nil t)
3190          (y-or-n-p "The article contains an Approved header.  Really post? ")
3191        t))
3192    ;; Check the Message-ID header.
3193    (message-check 'message-id
3194      (let* ((case-fold-search t)
3195             (message-id (message-fetch-field "message-id" t)))
3196        (or (not message-id)
3197            ;; Is there an @ in the ID?
3198            (and (string-match "@" message-id)
3199                 ;; Is there a dot in the ID?
3200                 (string-match "@[^.]*\\." message-id)
3201                 ;; Does the ID end with a dot?
3202                 (not (string-match "\\.>" message-id)))
3203            (y-or-n-p
3204             (format "The Message-ID looks strange: \"%s\".  Really post? "
3205                     message-id)))))
3206    ;; Check the Newsgroups & Followup-To headers.
3207    (message-check 'existing-newsgroups
3208      (let* ((case-fold-search t)
3209             (newsgroups (message-fetch-field "newsgroups"))
3210             (followup-to (message-fetch-field "followup-to"))
3211             (groups (message-tokenize-header
3212                      (if followup-to
3213                          (concat newsgroups "," followup-to)
3214                        newsgroups)))
3215             (post-method (if (message-functionp message-post-method)
3216                              (funcall message-post-method)
3217                            message-post-method))
3218             ;; KLUDGE to handle nnvirtual groups.  Doing this right
3219             ;; would probably involve a new nnoo function.
3220             ;; -- Per Abrahamsen <abraham@dina.kvl.dk>, 2001-10-17.
3221             (method (if (and (consp post-method) 
3222                              (eq (car post-method) 'nnvirtual)
3223                              gnus-message-group-art)
3224                         (let ((group (car (nnvirtual-find-group-art
3225                                            (car gnus-message-group-art)
3226                                            (cdr gnus-message-group-art)))))
3227                           (gnus-find-method-for-group group))
3228                       post-method))
3229             (known-groups
3230              (mapcar (lambda (n)
3231                        (gnus-group-name-decode 
3232                         (gnus-group-real-name n)
3233                         (gnus-group-name-charset method n)))
3234                      (gnus-groups-from-server method)))
3235             errors)
3236        (while groups
3237          (unless (or (equal (car groups) "poster")
3238                      (member (car groups) known-groups))
3239            (push (car groups) errors))
3240          (pop groups))
3241        (cond
3242         ;; Gnus is not running.
3243         ((or (not (and (boundp 'gnus-active-hashtb)
3244                        gnus-active-hashtb))
3245              (not (boundp 'gnus-read-active-file)))
3246          t)
3247         ;; We don't have all the group names.
3248         ((and (or (not gnus-read-active-file)
3249                   (eq gnus-read-active-file 'some))
3250               errors)
3251          (y-or-n-p
3252           (format
3253            "Really post to %s possibly unknown group%s: %s? "
3254            (if (= (length errors) 1) "this" "these")
3255            (if (= (length errors) 1) "" "s")
3256            (mapconcat 'identity errors ", "))))
3257         ;; There were no errors.
3258         ((not errors)
3259          t)
3260         ;; There are unknown groups.
3261         (t
3262          (y-or-n-p
3263           (format
3264            "Really post to %s unknown group%s: %s? "
3265            (if (= (length errors) 1) "this" "these")
3266            (if (= (length errors) 1) "" "s")
3267            (mapconcat 'identity errors ", ")))))))
3268    ;; Check the Newsgroups & Followup-To headers for syntax errors.
3269    (message-check 'valid-newsgroups
3270      (let ((case-fold-search t)
3271            (headers '("Newsgroups" "Followup-To"))
3272            header error)
3273        (while (and headers (not error))
3274          (when (setq header (mail-fetch-field (car headers)))
3275            (if (or
3276                 (not
3277                  (string-match
3278                   "\\`\\([-+_&.a-zA-Z0-9]+\\)?\\(,[-+_&.a-zA-Z0-9]+\\)*\\'"
3279                   header))
3280                 (memq
3281                  nil (mapcar
3282                       (lambda (g)
3283                         (not (string-match "\\.\\'\\|\\.\\." g)))
3284                       (message-tokenize-header header ","))))
3285                (setq error t)))
3286          (unless error
3287            (pop headers)))
3288        (if (not error)
3289            t
3290          (y-or-n-p
3291           (format "The %s header looks odd: \"%s\".  Really post? "
3292                   (car headers) header)))))
3293    (message-check 'repeated-newsgroups
3294      (let ((case-fold-search t)
3295            (headers '("Newsgroups" "Followup-To"))
3296            header error groups group)
3297        (while (and headers
3298                    (not error))
3299          (when (setq header (mail-fetch-field (pop headers)))
3300            (setq groups (message-tokenize-header header ","))
3301            (while (setq group (pop groups))
3302              (when (member group groups)
3303                (setq error group
3304                      groups nil)))))
3305        (if (not error)
3306            t
3307          (y-or-n-p
3308           (format "Group %s is repeated in headers.  Really post? " error)))))
3309    ;; Check the From header.
3310    (message-check 'from
3311      (let* ((case-fold-search t)
3312             (from (message-fetch-field "from"))
3313             ad)
3314        (cond
3315         ((not from)
3316          (message "There is no From line.  Posting is denied.")
3317          nil)
3318         ((or (not (string-match
3319                    "@[^\\.]*\\."
3320                    (setq ad (nth 1 (mail-extract-address-components
3321                                     from))))) ;larsi@ifi
3322              (string-match "\\.\\." ad) ;larsi@ifi..uio
3323              (string-match "@\\." ad)   ;larsi@.ifi.uio
3324              (string-match "\\.$" ad)   ;larsi@ifi.uio.
3325              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
3326              (string-match "(.*).*(.*)" from)) ;(lars) (lars)
3327          (message
3328           "Denied posting -- the From looks strange: \"%s\"." from)
3329          nil)
3330         ((let ((addresses (rfc822-addresses from)))
3331            (while (and addresses
3332                        (not (eq (string-to-char (car addresses)) ?\()))
3333              (setq addresses (cdr addresses)))
3334            addresses)
3335          (message
3336           "Denied posting -- bad From address: \"%s\"." from)
3337          nil)
3338         (t t))))
3339    ;; Check the Reply-To header.
3340    (message-check 'reply-to
3341      (let* ((case-fold-search t)
3342             (reply-to (message-fetch-field "reply-to"))
3343             ad)
3344        (cond
3345         ((not reply-to)
3346          t)
3347         ((string-match "," reply-to)
3348          (y-or-n-p
3349           (format "Multiple Reply-To addresses: \"%s\". Really post? "
3350                   reply-to)))
3351         ((or (not (string-match
3352                    "@[^\\.]*\\."
3353                    (setq ad (nth 1 (mail-extract-address-components
3354                                     reply-to))))) ;larsi@ifi
3355              (string-match "\\.\\." ad) ;larsi@ifi..uio
3356              (string-match "@\\." ad)   ;larsi@.ifi.uio
3357              (string-match "\\.$" ad)   ;larsi@ifi.uio.
3358              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
3359              (string-match "(.*).*(.*)" reply-to)) ;(lars) (lars)
3360          (y-or-n-p
3361           (format
3362            "The Reply-To looks strange: \"%s\". Really post? "
3363            reply-to)))
3364         (t t))))))
3365
3366 (defun message-check-news-body-syntax ()
3367   (and
3368    ;; Check for long lines.
3369    (message-check 'long-lines
3370      (goto-char (point-min))
3371      (re-search-forward
3372       (concat "^" (regexp-quote mail-header-separator) "$"))
3373      (forward-line 1)
3374      (while (and
3375              (or (looking-at
3376                   "<#\\(/\\)?\\(multipart\\|part\\|external\\|mml\\)")
3377                  (let ((p (point)))
3378                    (end-of-line)
3379                    (< (- (point) p) 80)))
3380              (zerop (forward-line 1))))
3381      (or (bolp)
3382          (eobp)
3383          (y-or-n-p
3384           "You have lines longer than 79 characters.  Really post? ")))
3385    ;; Check whether the article is empty.
3386    (message-check 'empty
3387      (goto-char (point-min))
3388      (re-search-forward
3389       (concat "^" (regexp-quote mail-header-separator) "$"))
3390      (forward-line 1)
3391      (let ((b (point)))
3392        (goto-char (point-max))
3393        (re-search-backward message-signature-separator nil t)
3394        (beginning-of-line)
3395        (or (re-search-backward "[^ \n\t]" b t)
3396            (if (message-gnksa-enable-p 'empty-article)
3397                (y-or-n-p "Empty article.  Really post? ")
3398              (message "Denied posting -- Empty article.")
3399              nil))))
3400    ;; Check for control characters.
3401    (message-check 'control-chars
3402      (if (re-search-forward "[\000-\007\013\015-\032\034-\037\200-\237]" nil t)
3403          (y-or-n-p
3404           "The article contains control characters.  Really post? ")
3405        t))
3406    ;; Check excessive size.
3407    (message-check 'size
3408      (if (> (buffer-size) 60000)
3409          (y-or-n-p
3410           (format "The article is %d octets long.  Really post? "
3411                   (buffer-size)))
3412        t))
3413    ;; Check whether any new text has been added.
3414    (message-check 'new-text
3415      (or
3416       (not message-checksum)
3417       (not (eq (message-checksum) message-checksum))
3418       (if (message-gnksa-enable-p 'quoted-text-only)
3419           (y-or-n-p
3420            "It looks like no new text has been added.  Really post? ")
3421         (message "Denied posting -- no new text has been added.")
3422         nil)))
3423    ;; Check the length of the signature.
3424    (message-check 'signature
3425      (goto-char (point-max))
3426      (if (> (count-lines (point) (point-max)) 5)
3427          (y-or-n-p
3428           (format
3429            "Your .sig is %d lines; it should be max 4.  Really post? "
3430            (1- (count-lines (point) (point-max)))))
3431        t))
3432    ;; Ensure that text follows last quoted portion.
3433    (message-check 'quoting-style
3434      (goto-char (point-max))
3435      (let ((no-problem t))
3436        (when (search-backward-regexp "^>[^\n]*\n" nil t)
3437          (setq no-problem (search-forward-regexp "^[ \t]*[^>\n]" nil t)))
3438        (if no-problem
3439            t
3440          (if (message-gnksa-enable-p 'quoted-text-only)
3441              (y-or-n-p "Your text should follow quoted text.  Really post? ")
3442            ;; Ensure that
3443            (goto-char (point-min))
3444            (re-search-forward
3445             (concat "^" (regexp-quote mail-header-separator) "$"))
3446            (if (search-forward-regexp "^[ \t]*[^>\n]" nil t)
3447                (y-or-n-p "Your text should follow quoted text.  Really post? ")
3448              (message "Denied posting -- only quoted text.")
3449              nil)))))))
3450
3451 (defun message-checksum ()
3452   "Return a \"checksum\" for the current buffer."
3453   (let ((sum 0))
3454     (save-excursion
3455       (goto-char (point-min))
3456       (re-search-forward
3457        (concat "^" (regexp-quote mail-header-separator) "$"))
3458       (while (not (eobp))
3459         (when (not (looking-at "[ \t\n]"))
3460           (setq sum (logxor (ash sum 1) (if (natnump sum) 0 1)
3461                             (char-after))))
3462         (forward-char 1)))
3463     sum))
3464
3465 (defun message-do-fcc ()
3466   "Process Fcc headers in the current buffer."
3467   (let ((case-fold-search t)
3468         (buf (current-buffer))
3469         list file
3470         (mml-externalize-attachments message-fcc-externalize-attachments))
3471     (save-excursion
3472       (save-restriction
3473         (message-narrow-to-headers)
3474         (setq file (message-fetch-field "fcc" t)))
3475       (when file
3476         (set-buffer (get-buffer-create " *message temp*"))
3477         (erase-buffer)
3478         (insert-buffer-substring buf)
3479         (message-encode-message-body)
3480         (save-restriction
3481           (message-narrow-to-headers)
3482           (while (setq file (message-fetch-field "fcc" t))
3483             (push file list)
3484             (message-remove-header "fcc" nil t))
3485           (let ((mail-parse-charset message-default-charset)
3486                 (rfc2047-header-encoding-alist
3487                  (cons '("Newsgroups" . default)
3488                        rfc2047-header-encoding-alist)))
3489             (mail-encode-encoded-word-buffer)))
3490         (goto-char (point-min))
3491         (when (re-search-forward
3492                (concat "^" (regexp-quote mail-header-separator) "$")
3493                nil t)
3494           (replace-match "" t t ))
3495         ;; Process FCC operations.
3496         (while list
3497           (setq file (pop list))
3498           (if (string-match "^[ \t]*|[ \t]*\\(.*\\)[ \t]*$" file)
3499               ;; Pipe the article to the program in question.
3500               (call-process-region (point-min) (point-max) shell-file-name
3501                                    nil nil nil shell-command-switch
3502                                    (match-string 1 file))
3503             ;; Save the article.
3504             (setq file (expand-file-name file))
3505             (unless (file-exists-p (file-name-directory file))
3506               (make-directory (file-name-directory file) t))
3507             (if (and message-fcc-handler-function
3508                      (not (eq message-fcc-handler-function 'rmail-output)))
3509                 (funcall message-fcc-handler-function file)
3510               (if (and (file-readable-p file) (mail-file-babyl-p file))
3511                   (rmail-output file 1 nil t)
3512                 (let ((mail-use-rfc822 t))
3513                   (rmail-output file 1 t t))))))
3514         (kill-buffer (current-buffer))))))
3515
3516 (defun message-output (filename)
3517   "Append this article to Unix/babyl mail file FILENAME."
3518   (if (and (file-readable-p filename)
3519            (mail-file-babyl-p filename))
3520       (gnus-output-to-rmail filename t)
3521     (gnus-output-to-mail filename t)))
3522
3523 (defun message-cleanup-headers ()
3524   "Do various automatic cleanups of the headers."
3525   ;; Remove empty lines in the header.
3526   (save-restriction
3527     (message-narrow-to-headers)
3528     ;; Remove blank lines.
3529     (while (re-search-forward "^[ \t]*\n" nil t)
3530       (replace-match "" t t))
3531
3532     ;; Correct Newsgroups and Followup-To headers:  Change sequence of
3533     ;; spaces to comma and eliminate spaces around commas.  Eliminate
3534     ;; embedded line breaks.
3535     (goto-char (point-min))
3536     (while (re-search-forward "^\\(Newsgroups\\|Followup-To\\): +" nil t)
3537       (save-restriction
3538         (narrow-to-region
3539          (point)
3540          (if (re-search-forward "^[^ \t]" nil t)
3541              (match-beginning 0)
3542            (forward-line 1)
3543            (point)))
3544         (goto-char (point-min))
3545         (while (re-search-forward "\n[ \t]+" nil t)
3546           (replace-match " " t t))     ;No line breaks (too confusing)
3547         (goto-char (point-min))
3548         (while (re-search-forward "[ \t\n]*,[ \t\n]*\\|[ \t]+" nil t)
3549           (replace-match "," t t))
3550         (goto-char (point-min))
3551         ;; Remove trailing commas.
3552         (when (re-search-forward ",+$" nil t)
3553           (replace-match "" t t))))))
3554
3555 (defun message-make-date (&optional now)
3556   "Make a valid data header.
3557 If NOW, use that time instead."
3558   (let* ((now (or now (current-time)))
3559          (zone (nth 8 (decode-time now)))
3560          (sign "+"))
3561     (when (< zone 0)
3562       (setq sign "-")
3563       (setq zone (- zone)))
3564     (concat
3565      ;; The day name of the %a spec is locale-specific.  Pfff.
3566      (format "%s, " (capitalize (car (rassoc (nth 6 (decode-time now))
3567                                              parse-time-weekdays))))
3568      (format-time-string "%d" now)
3569      ;; The month name of the %b spec is locale-specific.  Pfff.
3570      (format " %s "
3571              (capitalize (car (rassoc (nth 4 (decode-time now))
3572                                       parse-time-months))))
3573      (format-time-string "%Y %H:%M:%S " now)
3574      ;; We do all of this because XEmacs doesn't have the %z spec.
3575      (format "%s%02d%02d" sign (/ zone 3600) (/ (% zone 3600) 60)))))
3576
3577 (defun message-make-message-id ()
3578   "Make a unique Message-ID."
3579   (concat "<" (message-unique-id)
3580           (let ((psubject (save-excursion (message-fetch-field "subject")))
3581                 (psupersedes
3582                  (save-excursion (message-fetch-field "supersedes"))))
3583             (if (or
3584                  (and message-reply-headers
3585                       (mail-header-references message-reply-headers)
3586                       (mail-header-subject message-reply-headers)
3587                       psubject
3588                       (not (string=
3589                             (message-strip-subject-re
3590                              (mail-header-subject message-reply-headers))
3591                             (message-strip-subject-re psubject))))
3592                  (and psupersedes
3593                       (string-match "_-_@" psupersedes)))
3594                 "_-_" ""))
3595           "@" (message-make-fqdn) ">"))
3596
3597 (defvar message-unique-id-char nil)
3598
3599 ;; If you ever change this function, make sure the new version
3600 ;; cannot generate IDs that the old version could.
3601 ;; You might for example insert a "." somewhere (not next to another dot
3602 ;; or string boundary), or modify the "fsf" string.
3603 (defun message-unique-id ()
3604   ;; Don't use microseconds from (current-time), they may be unsupported.
3605   ;; Instead we use this randomly inited counter.
3606   (setq message-unique-id-char
3607         (% (1+ (or message-unique-id-char (logand (random t) (1- (lsh 1 20)))))
3608            ;; (current-time) returns 16-bit ints,
3609            ;; and 2^16*25 just fits into 4 digits i base 36.
3610            (* 25 25)))
3611   (let ((tm (current-time)))
3612     (concat
3613      (if (memq system-type '(ms-dos emx vax-vms))
3614          (let ((user (downcase (user-login-name))))
3615            (while (string-match "[^a-z0-9_]" user)
3616              (aset user (match-beginning 0) ?_))
3617            user)
3618        (message-number-base36 (user-uid) -1))
3619      (message-number-base36 (+ (car   tm)
3620                                (lsh (% message-unique-id-char 25) 16)) 4)
3621      (message-number-base36 (+ (nth 1 tm)
3622                                (lsh (/ message-unique-id-char 25) 16)) 4)
3623      ;; Append the newsreader name, because while the generated
3624      ;; ID is unique to this newsreader, other newsreaders might
3625      ;; otherwise generate the same ID via another algorithm.
3626      ".fsf")))
3627
3628 (defun message-number-base36 (num len)
3629   (if (if (< len 0)
3630           (<= num 0)
3631         (= len 0))
3632       ""
3633     (concat (message-number-base36 (/ num 36) (1- len))
3634             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
3635                                   (% num 36))))))
3636
3637 (defun message-make-organization ()
3638   "Make an Organization header."
3639   (let* ((organization
3640           (when message-user-organization
3641             (if (message-functionp message-user-organization)
3642                 (funcall message-user-organization)
3643               message-user-organization))))
3644     (save-excursion
3645       (message-set-work-buffer)
3646       (cond ((stringp organization)
3647              (insert organization))
3648             ((and (eq t organization)
3649                   message-user-organization-file
3650                   (file-exists-p message-user-organization-file))
3651              (insert-file-contents message-user-organization-file)))
3652       (goto-char (point-min))
3653       (while (re-search-forward "[\t\n]+" nil t)
3654         (replace-match "" t t))
3655       (unless (zerop (buffer-size))
3656         (buffer-string)))))
3657
3658 (defun message-make-lines ()
3659   "Count the number of lines and return numeric string."
3660   (save-excursion
3661     (save-restriction
3662       (widen)
3663       (message-goto-body)
3664       (int-to-string (count-lines (point) (point-max))))))
3665
3666 (defun message-make-in-reply-to ()
3667   "Return the In-Reply-To header for this message."
3668   (when message-reply-headers
3669     (let ((from (mail-header-from message-reply-headers))
3670           (date (mail-header-date message-reply-headers))
3671           (msg-id (mail-header-message-id message-reply-headers)))
3672       (when from
3673         (let ((stop-pos
3674                (string-match "  *at \\|  *@ \\| *(\\| *<" from)))
3675           (concat msg-id (if msg-id " (")
3676                   (if (and stop-pos
3677                            (not (zerop stop-pos)))
3678                       (substring from 0 stop-pos) from)
3679                   "'s message of \""
3680                   (if (or (not date) (string= date ""))
3681                       "(unknown date)" date)
3682                   "\"" (if msg-id ")")))))))
3683
3684 (defun message-make-distribution ()
3685   "Make a Distribution header."
3686   (let ((orig-distribution (message-fetch-reply-field "distribution")))
3687     (cond ((message-functionp message-distribution-function)
3688            (funcall message-distribution-function))
3689           (t orig-distribution))))
3690
3691 (defun message-make-expires ()
3692   "Return an Expires header based on `message-expires'."
3693   (let ((current (current-time))
3694         (future (* 1.0 message-expires 60 60 24)))
3695     ;; Add the future to current.
3696     (setcar current (+ (car current) (round (/ future (expt 2 16)))))
3697     (setcar (cdr current) (+ (nth 1 current) (% (round future) (expt 2 16))))
3698     (message-make-date current)))
3699
3700 (defun message-make-path ()
3701   "Return uucp path."
3702   (let ((login-name (user-login-name)))
3703     (cond ((null message-user-path)
3704            (concat (system-name) "!" login-name))
3705           ((stringp message-user-path)
3706            ;; Support GENERICPATH.  Suggested by vixie@decwrl.dec.com.
3707            (concat message-user-path "!" login-name))
3708           (t login-name))))
3709
3710 (defun message-make-from ()
3711   "Make a From header."
3712   (let* ((style message-from-style)
3713          (login (message-make-address))
3714          (fullname
3715           (or (and (boundp 'user-full-name)
3716                    user-full-name)
3717               (user-full-name))))
3718     (when (string= fullname "&")
3719       (setq fullname (user-login-name)))
3720     (save-excursion
3721       (message-set-work-buffer)
3722       (cond
3723        ((or (null style)
3724             (equal fullname ""))
3725         (insert login))
3726        ((or (eq style 'angles)
3727             (and (not (eq style 'parens))
3728                  ;; Use angles if no quoting is needed, or if parens would
3729                  ;; need quoting too.
3730                  (or (not (string-match "[^- !#-'*+/-9=?A-Z^-~]" fullname))
3731                      (let ((tmp (concat fullname nil)))
3732                        (while (string-match "([^()]*)" tmp)
3733                          (aset tmp (match-beginning 0) ?-)
3734                          (aset tmp (1- (match-end 0)) ?-))
3735                        (string-match "[\\()]" tmp)))))
3736         (insert fullname)
3737         (insert " <" login ">"))
3738        (t                               ; 'parens or default
3739         (insert login " (")
3740         (let ((fullname-start (point)))
3741           (insert fullname)
3742           (goto-char fullname-start)
3743           ;; RFC 822 says \ and nonmatching parentheses
3744           ;; must be escaped in comments.
3745           ;; Escape every instance of ()\ ...
3746           (while (re-search-forward "[()\\]" nil 1)
3747             (replace-match "\\\\\\&" t))
3748           ;; ... then undo escaping of matching parentheses,
3749           ;; including matching nested parentheses.
3750           (goto-char fullname-start)
3751           (while (re-search-forward
3752                   "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
3753                   nil 1)
3754             (replace-match "\\1(\\3)" t)
3755             (goto-char fullname-start)))
3756         (insert ")")))
3757       (buffer-string))))
3758
3759 (defun message-make-sender ()
3760   "Return the \"real\" user address.
3761 This function tries to ignore all user modifications, and
3762 give as trustworthy answer as possible."
3763   (concat (user-login-name) "@" (system-name)))
3764
3765 (defun message-make-address ()
3766   "Make the address of the user."
3767   (or (message-user-mail-address)
3768       (concat (user-login-name) "@" (message-make-domain))))
3769
3770 (defun message-user-mail-address ()
3771   "Return the pertinent part of `user-mail-address'."
3772   (when user-mail-address
3773     (if (string-match " " user-mail-address)
3774         (nth 1 (mail-extract-address-components user-mail-address))
3775       user-mail-address)))
3776
3777 (defun message-make-fqdn ()
3778   "Return user's fully qualified domain name."
3779   (let ((system-name (system-name))
3780         (user-mail (message-user-mail-address)))
3781     (cond
3782      ((and (string-match "[^.]\\.[^.]" system-name)
3783            (not (string-match message-bogus-system-names system-name)))
3784       ;; `system-name' returned the right result.
3785       system-name)
3786      ;; Try `mail-host-address'.
3787      ((and (boundp 'mail-host-address)
3788            (stringp mail-host-address)
3789            (string-match "\\." mail-host-address))
3790       mail-host-address)
3791      ;; We try `user-mail-address' as a backup.
3792      ((and user-mail
3793            (string-match "\\." user-mail)
3794            (string-match "@\\(.*\\)\\'" user-mail))
3795       (match-string 1 user-mail))
3796      ;; Default to this bogus thing.
3797      (t
3798       (concat system-name ".i-did-not-set--mail-host-address--so-tickle-me")))))
3799
3800 (defun message-make-host-name ()
3801   "Return the name of the host."
3802   (let ((fqdn (message-make-fqdn)))
3803     (string-match "^[^.]+\\." fqdn)
3804     (substring fqdn 0 (1- (match-end 0)))))
3805
3806 (defun message-make-domain ()
3807   "Return the domain name."
3808   (or mail-host-address
3809       (message-make-fqdn)))
3810
3811 (defun message-make-mft ()
3812   "Return the Mail-Followup-To header."
3813   (let* ((msg-recipients (message-options-get 'message-recipients))
3814          (recipients
3815           (mapcar 'mail-strip-quoted-names
3816                   (message-tokenize-header msg-recipients)))
3817          (file-regexps
3818           (if message-subscribed-address-file
3819               (let (begin end item re)
3820                 (save-excursion
3821                   (with-temp-buffer
3822                     (insert-file-contents message-subscribed-address-file)
3823                     (while (not (eobp))
3824                       (setq begin (point))
3825                       (forward-line 1)
3826                       (setq end (point))
3827                       (if (bolp) (setq end (1- end)))
3828                       (setq item (regexp-quote (buffer-substring begin end)))
3829                       (if re (setq re (concat re "\\|" item))
3830                         (setq re (concat "\\`\\(" item))))
3831                     (and re (list (concat re "\\)\\'"))))))))
3832          (mft-regexps (apply 'append message-subscribed-regexps
3833                              (mapcar 'regexp-quote
3834                                      message-subscribed-addresses)
3835                              file-regexps
3836                              (mapcar 'funcall
3837                                      message-subscribed-address-functions))))
3838     (save-match-data
3839       (when (eval (apply 'append '(or)
3840                          (mapcar
3841                           (function (lambda (regexp)
3842                                       (mapcar
3843                                        (function (lambda (recipient)
3844                                                    `(string-match ,regexp
3845                                                                   ,recipient)))
3846                                        recipients)))
3847                           mft-regexps)))
3848         msg-recipients))))
3849
3850 (defun message-generate-headers (headers)
3851   "Prepare article HEADERS.
3852 Headers already prepared in the buffer are not modified."
3853   (save-restriction
3854     (message-narrow-to-headers)
3855     (let* ((Date (message-make-date))
3856            (Message-ID (message-make-message-id))
3857            (Organization (message-make-organization))
3858            (From (message-make-from))
3859            (Path (message-make-path))
3860            (Subject nil)
3861            (Newsgroups nil)
3862            (In-Reply-To (message-make-in-reply-to))
3863            (To nil)
3864            (Distribution (message-make-distribution))
3865            (Lines (message-make-lines))
3866            (User-Agent message-newsreader)
3867            (Expires (message-make-expires))
3868            (case-fold-search t)
3869            header value elem)
3870       ;; First we remove any old generated headers.
3871       (let ((headers message-deletable-headers))
3872         (unless (buffer-modified-p)
3873           (setq headers (delq 'Message-ID (copy-sequence headers))))
3874         (while headers
3875           (goto-char (point-min))
3876           (and (re-search-forward
3877                 (concat "^" (symbol-name (car headers)) ": *") nil t)
3878                (get-text-property (1+ (match-beginning 0)) 'message-deletable)
3879                (message-delete-line))
3880           (pop headers)))
3881       ;; Go through all the required headers and see if they are in the
3882       ;; articles already.  If they are not, or are empty, they are
3883       ;; inserted automatically - except for Subject, Newsgroups and
3884       ;; Distribution.
3885       (while headers
3886         (goto-char (point-min))
3887         (setq elem (pop headers))
3888         (if (consp elem)
3889             (if (eq (car elem) 'optional)
3890                 (setq header (cdr elem))
3891               (setq header (car elem)))
3892           (setq header elem))
3893         (when (or (not (re-search-forward
3894                         (concat "^"
3895                                 (regexp-quote
3896                                  (downcase
3897                                   (if (stringp header)
3898                                       header
3899                                     (symbol-name header))))
3900                                 ":")
3901                         nil t))
3902                   (progn
3903                     ;; The header was found.  We insert a space after the
3904                     ;; colon, if there is none.
3905                     (if (/= (char-after) ? ) (insert " ") (forward-char 1))
3906                     ;; Find out whether the header is empty...
3907                     (looking-at "[ \t]*\n[^ \t]")))
3908           ;; So we find out what value we should insert.
3909           (setq value
3910                 (cond
3911                  ((and (consp elem) (eq (car elem) 'optional))
3912                   ;; This is an optional header.  If the cdr of this
3913                   ;; is something that is nil, then we do not insert
3914                   ;; this header.
3915                   (setq header (cdr elem))
3916                   (or (and (fboundp (cdr elem)) (funcall (cdr elem)))
3917                       (and (boundp (cdr elem)) (symbol-value (cdr elem)))))
3918                  ((consp elem)
3919                   ;; The element is a cons.  Either the cdr is a
3920                   ;; string to be inserted verbatim, or it is a
3921                   ;; function, and we insert the value returned from
3922                   ;; this function.
3923                   (or (and (stringp (cdr elem)) (cdr elem))
3924                       (and (fboundp (cdr elem)) (funcall (cdr elem)))))
3925                  ((and (boundp header) (symbol-value header))
3926                   ;; The element is a symbol.  We insert the value
3927                   ;; of this symbol, if any.
3928                   (symbol-value header))
3929                  ((not (message-check-element header))
3930                   ;; We couldn't generate a value for this header,
3931                   ;; so we just ask the user.
3932                   (read-from-minibuffer
3933                    (format "Empty header for %s; enter value: " header)))))
3934           ;; Finally insert the header.
3935           (when (and value
3936                      (not (equal value "")))
3937             (save-excursion
3938               (if (bolp)
3939                   (progn
3940                     ;; This header didn't exist, so we insert it.
3941                     (goto-char (point-max))
3942                     (insert (if (stringp header) header (symbol-name header))
3943                             ": " value)
3944                     ;; We check whether the value was ended by a
3945                     ;; newline.  If now, we insert one.
3946                     (unless (bolp)
3947                       (insert "\n"))
3948                     (forward-line -1))
3949                 ;; The value of this header was empty, so we clear
3950                 ;; totally and insert the new value.
3951                 (delete-region (point) (gnus-point-at-eol))
3952                 (insert value))
3953               ;; Add the deletable property to the headers that require it.
3954               (and (memq header message-deletable-headers)
3955                    (progn (beginning-of-line) (looking-at "[^:]+: "))
3956                    (add-text-properties
3957                     (point) (match-end 0)
3958                     '(message-deletable t face italic) (current-buffer)))))))
3959       ;; Insert new Sender if the From is strange.
3960       (let ((from (message-fetch-field "from"))
3961             (sender (message-fetch-field "sender"))
3962             (secure-sender (message-make-sender)))
3963         (when (and from
3964                    (not (message-check-element 'sender))
3965                    (not (string=
3966                          (downcase
3967                           (cadr (mail-extract-address-components from)))
3968                          (downcase secure-sender)))
3969                    (or (null sender)
3970                        (not
3971                         (string=
3972                          (downcase
3973                           (cadr (mail-extract-address-components sender)))
3974                          (downcase secure-sender)))))
3975           (goto-char (point-min))
3976           ;; Rename any old Sender headers to Original-Sender.
3977           (when (re-search-forward "^\\(Original-\\)*Sender:" nil t)
3978             (beginning-of-line)
3979             (insert "Original-")
3980             (beginning-of-line))
3981           (when (or (message-news-p)
3982                     (string-match "@.+\\.." secure-sender))
3983             (insert "Sender: " secure-sender "\n")))))))
3984
3985 (defun message-insert-courtesy-copy ()
3986   "Insert a courtesy message in mail copies of combined messages."
3987   (let (newsgroups)
3988     (save-excursion
3989       (save-restriction
3990         (message-narrow-to-headers)
3991         (when (setq newsgroups (message-fetch-field "newsgroups"))
3992           (goto-char (point-max))
3993           (insert "Posted-To: " newsgroups "\n")))
3994       (forward-line 1)
3995       (when message-courtesy-message
3996         (cond
3997          ((string-match "%s" message-courtesy-message)
3998           (insert (format message-courtesy-message newsgroups)))
3999          (t
4000           (insert message-courtesy-message)))))))
4001
4002 ;;;
4003 ;;; Setting up a message buffer
4004 ;;;
4005
4006 (defun message-fill-address (header value)
4007   (save-restriction
4008     (narrow-to-region (point) (point))
4009     (insert (capitalize (symbol-name header))
4010             ": "
4011             (if (consp value) (car value) value)
4012             "\n")
4013     (narrow-to-region (point-min) (1- (point-max)))
4014     (let (quoted last)
4015       (goto-char (point-min))
4016       (while (not (eobp))
4017         (skip-chars-forward "^,\"" (point-max))
4018         (if (or (eq (char-after) ?,)
4019                 (eobp))
4020             (when (not quoted)
4021               (if (and (> (current-column) 78)
4022                        last)
4023                   (progn
4024                     (save-excursion
4025                       (goto-char last)
4026                       (insert "\n\t"))
4027                     (setq last (1+ (point))))
4028                 (setq last (1+ (point)))))
4029           (setq quoted (not quoted)))
4030         (unless (eobp)
4031           (forward-char 1))))
4032     (goto-char (point-max))
4033     (widen)
4034     (forward-line 1)))
4035
4036 (defun message-fill-header (header value)
4037   (let ((begin (point))
4038         (fill-column 78)
4039         (fill-prefix "\t"))
4040     (insert (capitalize (symbol-name header))
4041             ": "
4042             (if (consp value) (car value) value)
4043             "\n")
4044     (save-restriction
4045       (narrow-to-region begin (point))
4046       (fill-region-as-paragraph begin (point))
4047       ;; Tapdance around looong Message-IDs.
4048       (forward-line -1)
4049       (when (looking-at "[ \t]*$")
4050         (message-delete-line))
4051       (goto-char begin)
4052       (re-search-forward ":" nil t)
4053       (when (looking-at "\n[ \t]+")
4054         (replace-match " " t t))
4055       (goto-char (point-max)))))
4056
4057 (defun message-shorten-1 (list cut surplus)
4058   "Cut SURPLUS elements out of LIST, beginning with CUTth one."
4059   (setcdr (nthcdr (- cut 2) list)
4060           (nthcdr (+ (- cut 2) surplus 1) list)))
4061
4062 (defun message-shorten-references (header references)
4063   "Trim REFERENCES to be 21 Message-ID long or less, and fold them.
4064 If folding is disallowed, also check that the REFERENCES are less
4065 than 988 characters long, and if they are not, trim them until they are."
4066   (let ((maxcount 21)
4067         (count 0)
4068         (cut 2)
4069         refs)
4070     (with-temp-buffer
4071       (insert references)
4072       (goto-char (point-min))
4073       ;; Cons a list of valid references.
4074       (while (re-search-forward "<[^>]+>" nil t)
4075         (push (match-string 0) refs))
4076       (setq refs (nreverse refs)
4077             count (length refs)))
4078
4079     ;; If the list has more than MAXCOUNT elements, trim it by
4080     ;; removing the CUTth element and the required number of
4081     ;; elements that follow.
4082     (when (> count maxcount)
4083       (let ((surplus (- count maxcount)))
4084         (message-shorten-1 refs cut surplus)
4085         (decf count surplus)))
4086
4087     ;; If folding is disallowed, make sure the total length (including
4088     ;; the spaces between) will be less than MAXSIZE characters.
4089     ;;
4090     ;; Only disallow folding for News messages. At this point the headers
4091     ;; have not been generated, thus we use message-this-is-news directly.
4092     (when (and message-this-is-news message-cater-to-broken-inn)
4093       (let ((maxsize 988)
4094             (totalsize (+ (apply #'+ (mapcar #'length refs))
4095                           (1- count)))
4096             (surplus 0)
4097             (ptr (nthcdr (1- cut) refs)))
4098         ;; Decide how many elements to cut off...
4099         (while (> totalsize maxsize)
4100           (decf totalsize (1+ (length (car ptr))))
4101           (incf surplus)
4102           (setq ptr (cdr ptr)))
4103         ;; ...and do it.
4104         (when (> surplus 0)
4105           (message-shorten-1 refs cut surplus))))
4106
4107     ;; Finally, collect the references back into a string and insert
4108     ;; it into the buffer.
4109     (let ((refstring (mapconcat #'identity refs " ")))
4110       (if (and message-this-is-news message-cater-to-broken-inn)
4111           (insert (capitalize (symbol-name header)) ": "
4112                   refstring "\n")
4113         (message-fill-header header refstring)))))
4114
4115 (defun message-position-point ()
4116   "Move point to where the user probably wants to find it."
4117   (message-narrow-to-headers)
4118   (cond
4119    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
4120     (search-backward ":" )
4121     (widen)
4122     (forward-char 1)
4123     (if (eq (char-after) ? )
4124         (forward-char 1)
4125       (insert " ")))
4126    (t
4127     (goto-char (point-max))
4128     (widen)
4129     (forward-line 1)
4130     (unless (looking-at "$")
4131       (forward-line 2)))
4132    (sit-for 0)))
4133
4134 (defun message-beginning-of-line (&optional n)
4135   "Move point to beginning of header value or to beginning of line."
4136   (interactive "p")
4137   (if (message-point-in-header-p)
4138       (let* ((here (point))
4139              (bol (progn (beginning-of-line n) (point)))
4140              (eol (gnus-point-at-eol))
4141              (eoh (re-search-forward ": *" eol t)))
4142         (if (or (not eoh) (equal here eoh))
4143             (goto-char bol)
4144           (goto-char eoh)))
4145     (beginning-of-line n)))
4146
4147 (defun message-buffer-name (type &optional to group)
4148   "Return a new (unique) buffer name based on TYPE and TO."
4149   (cond
4150    ;; Generate a new buffer name The Message Way.
4151    ((eq message-generate-new-buffers 'unique)
4152     (generate-new-buffer-name
4153      (concat "*" type
4154              (if to
4155                  (concat " to "
4156                          (or (car (mail-extract-address-components to))
4157                              to) "")
4158                "")
4159              (if (and group (not (string= group ""))) (concat " on " group) "")
4160              "*")))
4161    ;; Check whether `message-generate-new-buffers' is a function,
4162    ;; and if so, call it.
4163    ((message-functionp message-generate-new-buffers)
4164     (funcall message-generate-new-buffers type to group))
4165    ((eq message-generate-new-buffers 'unsent)
4166     (generate-new-buffer-name
4167      (concat "*unsent " type
4168              (if to
4169                  (concat " to "
4170                          (or (car (mail-extract-address-components to))
4171                              to) "")
4172                "")
4173              (if (and group (not (string= group ""))) (concat " on " group) "")
4174              "*")))
4175    ;; Use standard name.
4176    (t
4177     (format "*%s message*" type))))
4178
4179 (defun message-pop-to-buffer (name)
4180   "Pop to buffer NAME, and warn if it already exists and is modified."
4181   (let ((buffer (get-buffer name)))
4182     (if (and buffer
4183              (buffer-name buffer))
4184         (progn
4185           (set-buffer (pop-to-buffer buffer))
4186           (when (and (buffer-modified-p)
4187                      (not (y-or-n-p
4188                            "Message already being composed; erase? ")))
4189             (error "Message being composed")))
4190       (set-buffer (pop-to-buffer name)))
4191     (erase-buffer)
4192     (message-mode)))
4193
4194 (defun message-do-send-housekeeping ()
4195   "Kill old message buffers."
4196   ;; We might have sent this buffer already.  Delete it from the
4197   ;; list of buffers.
4198   (setq message-buffer-list (delq (current-buffer) message-buffer-list))
4199   (while (and message-max-buffers
4200               message-buffer-list
4201               (>= (length message-buffer-list) message-max-buffers))
4202     ;; Kill the oldest buffer -- unless it has been changed.
4203     (let ((buffer (pop message-buffer-list)))
4204       (when (and (buffer-name buffer)
4205                  (not (buffer-modified-p buffer)))
4206         (kill-buffer buffer))))
4207   ;; Rename the buffer.
4208   (if message-send-rename-function
4209       (funcall message-send-rename-function)
4210     ;; Note: mail-abbrevs of XEmacs renames buffer name behind Gnus.
4211     (when (string-match
4212            "\\`\\*\\(sent \\|unsent \\)?\\(.+\\)\\*[^\\*]*\\|\\`mail to "
4213            (buffer-name))
4214       (let ((name (match-string 2 (buffer-name)))
4215             to group)
4216         (if (not (or (null name)
4217                      (string-equal name "mail")
4218                      (string-equal name "posting")))
4219             (setq name (concat "*sent " name "*"))
4220           (message-narrow-to-headers)
4221           (setq to (message-fetch-field "to"))
4222           (setq group (message-fetch-field "newsgroups"))
4223           (widen)
4224           (setq name
4225                 (cond
4226                  (to (concat "*sent mail to "
4227                              (or (car (mail-extract-address-components to))
4228                                  to) "*"))
4229                  ((and group (not (string= group "")))
4230                   (concat "*sent posting on " group "*"))
4231                  (t "*sent mail*"))))
4232         (unless (string-equal name (buffer-name))
4233           (rename-buffer name t)))))
4234   ;; Push the current buffer onto the list.
4235   (when message-max-buffers
4236     (setq message-buffer-list
4237           (nconc message-buffer-list (list (current-buffer))))))
4238
4239 (defun message-mail-user-agent ()
4240   (let ((mua (cond
4241               ((not message-mail-user-agent) nil)
4242               ((eq message-mail-user-agent t) mail-user-agent)
4243               (t message-mail-user-agent))))
4244     (if (memq mua '(message-user-agent gnus-user-agent))
4245         nil
4246       mua)))
4247
4248 (defun message-setup (headers &optional replybuffer actions switch-function)
4249   (let ((mua (message-mail-user-agent))
4250         subject to field yank-action)
4251     (if (not (and message-this-is-mail mua))
4252         (message-setup-1 headers replybuffer actions)
4253       (if replybuffer
4254           (setq yank-action (list 'insert-buffer replybuffer)))
4255       (setq headers (copy-sequence headers))
4256       (setq field (assq 'Subject headers))
4257       (when field
4258         (setq subject (cdr field))
4259         (setq headers (delq field headers)))
4260       (setq field (assq 'To headers))
4261       (when field
4262         (setq to (cdr field))
4263         (setq headers (delq field headers)))
4264       (let ((mail-user-agent mua))
4265         (compose-mail to subject
4266                       (mapcar (lambda (item)
4267                                 (cons
4268                                  (format "%s" (car item))
4269                                  (cdr item)))
4270                               headers)
4271                       nil switch-function yank-action actions)))))
4272
4273 (defun message-setup-1 (headers &optional replybuffer actions)
4274   (dolist (action actions)
4275     (condition-case nil
4276         (add-to-list 'message-send-actions
4277                      `(apply ',(car action) ',(cdr action)))))
4278   (setq message-reply-buffer replybuffer)
4279   (goto-char (point-min))
4280   ;; Insert all the headers.
4281   (mail-header-format
4282    (let ((h headers)
4283          (alist message-header-format-alist))
4284      (while h
4285        (unless (assq (caar h) message-header-format-alist)
4286          (push (list (caar h)) alist))
4287        (pop h))
4288      alist)
4289    headers)
4290   (delete-region (point) (progn (forward-line -1) (point)))
4291   (when message-default-headers
4292     (insert message-default-headers)
4293     (or (bolp) (insert ?\n)))
4294   (put-text-property
4295    (point)
4296    (progn
4297      (insert mail-header-separator "\n")
4298      (1- (point)))
4299    'read-only nil)
4300   (forward-line -1)
4301   (when (message-news-p)
4302     (when message-default-news-headers
4303       (insert message-default-news-headers)
4304       (or (bolp) (insert ?\n)))
4305     (when message-generate-headers-first
4306       (message-generate-headers
4307        (delq 'Lines
4308              (delq 'Subject
4309                    (copy-sequence message-required-news-headers))))))
4310   (when (message-mail-p)
4311     (when message-default-mail-headers
4312       (insert message-default-mail-headers)
4313       (or (bolp) (insert ?\n)))
4314     (when message-generate-headers-first
4315       (message-generate-headers
4316        (delq 'Lines
4317              (delq 'Subject
4318                    (copy-sequence message-required-mail-headers))))))
4319   (run-hooks 'message-signature-setup-hook)
4320   (message-insert-signature)
4321   (save-restriction
4322     (message-narrow-to-headers)
4323     (if message-alternative-emails
4324         (message-use-alternative-email-as-from))
4325     (run-hooks 'message-header-setup-hook))
4326   (set-buffer-modified-p nil)
4327   (setq buffer-undo-list nil)
4328   (run-hooks 'message-setup-hook)
4329   (message-position-point)
4330   (undo-boundary))
4331
4332 (defun message-set-auto-save-file-name ()
4333   "Associate the message buffer with a file in the drafts directory."
4334   (when message-auto-save-directory
4335     (unless (file-directory-p
4336              (directory-file-name message-auto-save-directory))
4337       (gnus-make-directory message-auto-save-directory))
4338     (if (gnus-alive-p)
4339         (setq message-draft-article
4340               (nndraft-request-associate-buffer "drafts"))
4341       (setq buffer-file-name (expand-file-name
4342                               (if (memq system-type 
4343                                         '(ms-dos ms-windows windows-nt 
4344                                                  cygwin32 win32 w32 
4345                                                  mswindows))
4346                                   "message"
4347                                 "*message*")
4348                               message-auto-save-directory))
4349       (setq buffer-auto-save-file-name (make-auto-save-file-name)))
4350     (clear-visited-file-modtime)
4351     (setq buffer-file-coding-system message-draft-coding-system)))
4352
4353 (defun message-disassociate-draft ()
4354   "Disassociate the message buffer from the drafts directory."
4355   (when message-draft-article
4356     (nndraft-request-expire-articles
4357      (list message-draft-article) "drafts" nil t)))
4358
4359 (defun message-insert-headers ()
4360   "Generate the headers for the article."
4361   (interactive)
4362   (save-excursion
4363     (save-restriction
4364       (message-narrow-to-headers)
4365       (when (message-news-p)
4366         (message-generate-headers
4367          (delq 'Lines
4368                (delq 'Subject
4369                      (copy-sequence message-required-news-headers)))))
4370       (when (message-mail-p)
4371         (message-generate-headers
4372          (delq 'Lines
4373                (delq 'Subject
4374                      (copy-sequence message-required-mail-headers))))))))
4375
4376 \f
4377
4378 ;;;
4379 ;;; Commands for interfacing with message
4380 ;;;
4381
4382 ;;;###autoload
4383 (defun message-mail (&optional to subject
4384                                other-headers continue switch-function
4385                                yank-action send-actions)
4386   "Start editing a mail message to be sent.
4387 OTHER-HEADERS is an alist of header/value pairs."
4388   (interactive)
4389   (let ((message-this-is-mail t) replybuffer)
4390     (unless (message-mail-user-agent)
4391       (message-pop-to-buffer (message-buffer-name "mail" to)))
4392     ;; FIXME: message-mail should do something if YANK-ACTION is not
4393     ;; insert-buffer.
4394     (and (consp yank-action) (eq (car yank-action) 'insert-buffer)
4395          (setq replybuffer (nth 1 yank-action)))
4396     (message-setup
4397      (nconc
4398       `((To . ,(or to "")) (Subject . ,(or subject "")))
4399       (when other-headers other-headers))
4400      replybuffer send-actions)
4401     ;; FIXME: Should return nil if failure.
4402     t))
4403
4404 ;;;###autoload
4405 (defun message-news (&optional newsgroups subject)
4406   "Start editing a news article to be sent."
4407   (interactive)
4408   (let ((message-this-is-news t))
4409     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups))
4410     (message-setup `((Newsgroups . ,(or newsgroups ""))
4411                      (Subject . ,(or subject ""))))))
4412
4413 (defun message-get-reply-headers (wide &optional to-address)
4414   (let (follow-to mct never-mct to cc author mft recipients)
4415     ;; Find all relevant headers we need.
4416     (setq to (message-fetch-field "to")
4417           cc (message-fetch-field "cc")
4418           mct (message-fetch-field "mail-copies-to")
4419           author (or (message-fetch-field "mail-reply-to")
4420                      (message-fetch-field "reply-to")
4421                      (message-fetch-field "from")
4422                      "")
4423           mft (and message-use-mail-followup-to
4424                    (message-fetch-field "mail-followup-to")))
4425
4426     ;; Handle special values of Mail-Copies-To.
4427     (when mct
4428       (cond ((or (equal (downcase mct) "never")
4429                  (equal (downcase mct) "nobody"))
4430              (setq never-mct t)
4431              (setq mct nil))
4432             ((or (equal (downcase mct) "always")
4433                  (equal (downcase mct) "poster"))
4434              (setq mct author))))
4435
4436     (save-match-data
4437       ;; Build (textual) list of new recipient addresses.
4438       (cond
4439        ((not wide)
4440         (setq recipients (concat ", " author)))
4441        ((and mft
4442              (string-match "[^ \t,]" mft)
4443              (or (not (eq message-use-mail-followup-to 'ask))
4444                  (message-y-or-n-p "Obey Mail-Followup-To? " t "\
4445 You should normally obey the Mail-Followup-To: header.  In this
4446 article, it has the value of
4447
4448 " mft "
4449
4450 which directs your response to " (if (string-match "," mft)
4451                                      "the specified addresses"
4452                                    "that address only") ".
4453
4454 Most commonly, Mail-Followup-To is used by a mailing list poster to
4455 express that responses should be sent to just the list, and not the
4456 poster as well.
4457
4458 If a message is posted to several mailing lists, Mail-Followup-To may
4459 also be used to direct the following discussion to one list only,
4460 because discussions that are spread over several lists tend to be
4461 fragmented and very difficult to follow.
4462
4463 Also, some source/announcement lists are not intended for discussion;
4464 responses here are directed to other addresses.")))
4465         (setq recipients (concat ", " mft)))
4466        (to-address
4467         (setq recipients (concat ", " to-address))
4468         ;; If the author explicitly asked for a copy, we don't deny it to them.
4469         (if mct (setq recipients (concat recipients ", " mct))))
4470        (t
4471         (setq recipients (if never-mct "" (concat ", " author)))
4472         (if to  (setq recipients (concat recipients ", " to)))
4473         (if cc  (setq recipients (concat recipients ", " cc)))
4474         (if mct (setq recipients (concat recipients ", " mct)))))
4475       (if (>= (length recipients) 2)
4476           ;; Strip the leading ", ".
4477           (setq recipients (substring recipients 2)))
4478       ;; Squeeze whitespace.
4479       (while (string-match "[ \t][ \t]+" recipients)
4480         (setq recipients (replace-match " " t t recipients)))
4481       ;; Remove addresses that match `rmail-dont-reply-to-names'.
4482       (let ((rmail-dont-reply-to-names message-dont-reply-to-names))
4483         (setq recipients (rmail-dont-reply-to recipients)))
4484       ;; Perhaps "Mail-Copies-To: never" removed the only address?
4485       (if (string-equal recipients "")
4486           (setq recipients author))
4487       ;; Convert string to a list of (("foo@bar" . "Name <foo@bar>") ...).
4488       (setq recipients
4489             (mapcar
4490              (lambda (addr)
4491                (cons (mail-strip-quoted-names addr) addr))
4492              (message-tokenize-header recipients)))
4493       ;; Remove first duplicates.  (Why not all duplicates?  Is this a bug?)
4494       (let ((s recipients))
4495         (while s
4496           (setq recipients (delq (assoc (car (pop s)) s) recipients))))
4497       ;; Build the header alist.  Allow the user to be asked whether
4498       ;; or not to reply to all recipients in a wide reply.
4499       (setq follow-to (list (cons 'To (cdr (pop recipients)))))
4500       (when (and recipients
4501                  (or (not message-wide-reply-confirm-recipients)
4502                      (y-or-n-p "Reply to all recipients? ")))
4503         (setq recipients (mapconcat
4504                           (lambda (addr) (cdr addr)) recipients ", "))
4505         (if (string-match "^ +" recipients)
4506             (setq recipients (substring recipients (match-end 0))))
4507         (push (cons 'Cc recipients) follow-to)))
4508     follow-to))
4509
4510 ;;;###autoload
4511 (defun message-reply (&optional to-address wide)
4512   "Start editing a reply to the article in the current buffer."
4513   (interactive)
4514   (require 'gnus-sum)                   ; for gnus-list-identifiers
4515   (let ((cur (current-buffer))
4516         from subject date reply-to to cc
4517         references message-id follow-to
4518         (inhibit-point-motion-hooks t)
4519         (message-this-is-mail t)
4520         gnus-warning)
4521     (save-restriction
4522       (message-narrow-to-head-1)
4523       ;; Allow customizations to have their say.
4524       (if (not wide)
4525           ;; This is a regular reply.
4526           (when (message-functionp message-reply-to-function)
4527             (save-excursion
4528               (setq follow-to (funcall message-reply-to-function))))
4529         ;; This is a followup.
4530         (when (message-functionp message-wide-reply-to-function)
4531           (save-excursion
4532             (setq follow-to
4533                   (funcall message-wide-reply-to-function)))))
4534       (setq message-id (message-fetch-field "message-id" t)
4535             references (message-fetch-field "references")
4536             date (message-fetch-field "date")
4537             from (message-fetch-field "from")
4538             subject (or (message-fetch-field "subject") "none"))
4539       (when gnus-list-identifiers
4540         (setq subject (message-strip-list-identifiers subject)))
4541       (setq subject (concat "Re: " (message-strip-subject-re subject)))
4542
4543       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
4544                  (string-match "<[^>]+>" gnus-warning))
4545         (setq message-id (match-string 0 gnus-warning)))
4546
4547       (unless follow-to
4548         (setq follow-to (message-get-reply-headers wide to-address))))
4549
4550     (unless (message-mail-user-agent)
4551       (message-pop-to-buffer
4552        (message-buffer-name
4553         (if wide "wide reply" "reply") from
4554         (if wide to-address nil))))
4555
4556     (setq message-reply-headers
4557           (vector 0 subject from date message-id references 0 0 ""))
4558
4559     (message-setup
4560      `((Subject . ,subject)
4561        ,@follow-to
4562        ,@(if (or references message-id)
4563              `((References . ,(concat (or references "") (and references " ")
4564                                       (or message-id ""))))
4565            nil))
4566      cur)))
4567
4568 ;;;###autoload
4569 (defun message-wide-reply (&optional to-address)
4570   "Make a \"wide\" reply to the message in the current buffer."
4571   (interactive)
4572   (message-reply to-address t))
4573
4574 ;;;###autoload
4575 (defun message-followup (&optional to-newsgroups)
4576   "Follow up to the message in the current buffer.
4577 If TO-NEWSGROUPS, use that as the new Newsgroups line."
4578   (interactive)
4579   (require 'gnus-sum)                   ; for gnus-list-identifiers
4580   (let ((cur (current-buffer))
4581         from subject date reply-to mrt mct
4582         references message-id follow-to
4583         (inhibit-point-motion-hooks t)
4584         (message-this-is-news t)
4585         followup-to distribution newsgroups gnus-warning posted-to)
4586     (save-restriction
4587       (narrow-to-region
4588        (goto-char (point-min))
4589        (if (search-forward "\n\n" nil t)
4590            (1- (point))
4591          (point-max)))
4592       (when (message-functionp message-followup-to-function)
4593         (setq follow-to
4594               (funcall message-followup-to-function)))
4595       (setq from (message-fetch-field "from")
4596             date (message-fetch-field "date")
4597             subject (or (message-fetch-field "subject") "none")
4598             references (message-fetch-field "references")
4599             message-id (message-fetch-field "message-id" t)
4600             followup-to (message-fetch-field "followup-to")
4601             newsgroups (message-fetch-field "newsgroups")
4602             posted-to (message-fetch-field "posted-to")
4603             reply-to (message-fetch-field "reply-to")
4604             mrt (message-fetch-field "mail-reply-to")
4605             distribution (message-fetch-field "distribution")
4606             mct (message-fetch-field "mail-copies-to"))
4607       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
4608                  (string-match "<[^>]+>" gnus-warning))
4609         (setq message-id (match-string 0 gnus-warning)))
4610       ;; Remove bogus distribution.
4611       (when (and (stringp distribution)
4612                  (let ((case-fold-search t))
4613                    (string-match "world" distribution)))
4614         (setq distribution nil))
4615       (if gnus-list-identifiers
4616           (setq subject (message-strip-list-identifiers subject)))
4617       (setq subject (concat "Re: " (message-strip-subject-re subject)))
4618       (widen))
4619
4620     (message-pop-to-buffer (message-buffer-name "followup" from newsgroups))
4621
4622     (message-setup
4623      `((Subject . ,subject)
4624        ,@(cond
4625           (to-newsgroups
4626            (list (cons 'Newsgroups to-newsgroups)))
4627           (follow-to follow-to)
4628           ((and followup-to message-use-followup-to)
4629            (list
4630             (cond
4631              ((equal (downcase followup-to) "poster")
4632               (if (or (eq message-use-followup-to 'use)
4633                       (message-y-or-n-p "Obey Followup-To: poster? " t "\
4634 You should normally obey the Followup-To: header.
4635
4636 `Followup-To: poster' sends your response via e-mail instead of news.
4637
4638 A typical situation where `Followup-To: poster' is used is when the poster
4639 does not read the newsgroup, so he wouldn't see any replies sent to it."))
4640                   (progn
4641                     (setq message-this-is-news nil)
4642                     (cons 'To (or mrt reply-to from "")))
4643                 (cons 'Newsgroups newsgroups)))
4644              (t
4645               (if (or (equal followup-to newsgroups)
4646                       (not (eq message-use-followup-to 'ask))
4647                       (message-y-or-n-p
4648                        (concat "Obey Followup-To: " followup-to "? ") t "\
4649 You should normally obey the Followup-To: header.
4650
4651         `Followup-To: " followup-to "'
4652 directs your response to " (if (string-match "," followup-to)
4653                                "the specified newsgroups"
4654                              "that newsgroup only") ".
4655
4656 If a message is posted to several newsgroups, Followup-To is often
4657 used to direct the following discussion to one newsgroup only,
4658 because discussions that are spread over several newsgroup tend to
4659 be fragmented and very difficult to follow.
4660
4661 Also, some source/announcement newsgroups are not intended for discussion;
4662 responses here are directed to other newsgroups."))
4663                   (cons 'Newsgroups followup-to)
4664                 (cons 'Newsgroups newsgroups))))))
4665           (posted-to
4666            `((Newsgroups . ,posted-to)))
4667           (t
4668            `((Newsgroups . ,newsgroups))))
4669        ,@(and distribution (list (cons 'Distribution distribution)))
4670        ,@(if (or references message-id)
4671              `((References . ,(concat (or references "") (and references " ")
4672                                       (or message-id "")))))
4673        ,@(when (and mct
4674                     (not (or (equal (downcase mct) "never")
4675                              (equal (downcase mct) "nobody"))))
4676            (list (cons 'Cc (if (or (equal (downcase mct) "always")
4677                                    (equal (downcase mct) "poster"))
4678                                (or mrt reply-to from "")
4679                              mct)))))
4680
4681      cur)
4682
4683     (setq message-reply-headers
4684           (vector 0 subject from date message-id references 0 0 ""))))
4685
4686
4687 ;;;###autoload
4688 (defun message-cancel-news (&optional arg)
4689   "Cancel an article you posted.
4690 If ARG, allow editing of the cancellation message."
4691   (interactive "P")
4692   (unless (message-news-p)
4693     (error "This is not a news article; canceling is impossible"))
4694   (let (from newsgroups message-id distribution buf sender)
4695     (save-excursion
4696       ;; Get header info from original article.
4697       (save-restriction
4698         (message-narrow-to-head-1)
4699         (setq from (message-fetch-field "from")
4700               sender (message-fetch-field "sender")
4701               newsgroups (message-fetch-field "newsgroups")
4702               message-id (message-fetch-field "message-id" t)
4703               distribution (message-fetch-field "distribution")))
4704       ;; Make sure that this article was written by the user.
4705       (unless (or
4706                ;; Canlock-logic as suggested by Per Abrahamsen
4707                ;; <abraham@dina.kvl.dk>
4708                ;;
4709                ;; IF article has cancel-lock THEN
4710                ;;   IF we can verify it THEN
4711                ;;     issue cancel
4712                ;;   ELSE
4713                ;;     error: cancellock: article is not yours
4714                ;; ELSE
4715                ;;   Use old rules, comparing sender...
4716                (if (message-fetch-field "Cancel-Lock")
4717                    (if (null (canlock-verify))
4718                        t
4719                      (error "Failed to verify Cancel-lock: This article is not yours"))
4720                  nil)
4721                (message-gnksa-enable-p 'cancel-messages)
4722                (and sender
4723                     (string-equal
4724                      (downcase sender)
4725                      (downcase (message-make-sender))))
4726                (string-equal
4727                 (downcase (cadr (mail-extract-address-components from)))
4728                 (downcase (cadr (mail-extract-address-components
4729                                  (message-make-from))))))
4730         (error "This article is not yours"))
4731       (when (yes-or-no-p "Do you really want to cancel this article? ")
4732         ;; Make control message.
4733         (if arg
4734             (message-news)
4735           (setq buf (set-buffer (get-buffer-create " *message cancel*"))))
4736         (erase-buffer)
4737         (insert "Newsgroups: " newsgroups "\n"
4738                 "From: " from "\n"
4739                 "Subject: cmsg cancel " message-id "\n"
4740                 "Control: cancel " message-id "\n"
4741                 (if distribution
4742                     (concat "Distribution: " distribution "\n")
4743                   "")
4744                 mail-header-separator "\n"
4745                 message-cancel-message)
4746         (run-hooks 'message-cancel-hook)
4747         (unless arg
4748           (message "Canceling your article...")
4749           (if (let ((message-syntax-checks
4750                      'dont-check-for-anything-just-trust-me))
4751                 (funcall message-send-news-function))
4752               (message "Canceling your article...done"))
4753           (kill-buffer buf))))))
4754
4755 ;;;###autoload
4756 (defun message-supersede ()
4757   "Start composing a message to supersede the current message.
4758 This is done simply by taking the old article and adding a Supersedes
4759 header line with the old Message-ID."
4760   (interactive)
4761   (let ((cur (current-buffer))
4762         (sender (message-fetch-field "sender"))
4763         (from (message-fetch-field "from")))
4764     ;; Check whether the user owns the article that is to be superseded.
4765     (unless (or
4766              ;; Canlock-logic as suggested by Per Abrahamsen
4767              ;; <abraham@dina.kvl.dk>
4768              ;;
4769              ;; IF article has cancel-lock THEN
4770              ;;   IF we can verify it THEN
4771              ;;     issue cancel
4772              ;;   ELSE
4773              ;;     error: cancellock: article is not yours
4774              ;; ELSE
4775              ;;   Use old rules, comparing sender...
4776              (if (message-fetch-field "Cancel-Lock")
4777                  (if (null (canlock-verify))
4778                      t
4779                    (error "Failed to verify Cancel-lock: This article is not yours"))
4780                nil)
4781              (message-gnksa-enable-p 'cancel-messages)
4782                 (and sender
4783                      (string-equal
4784                       (downcase sender)
4785                       (downcase (message-make-sender))))
4786                 (string-equal
4787                  (downcase (cadr (mail-extract-address-components from)))
4788                  (downcase (cadr (mail-extract-address-components
4789                                   (message-make-from))))))
4790       (error "This article is not yours"))
4791     ;; Get a normal message buffer.
4792     (message-pop-to-buffer (message-buffer-name "supersede"))
4793     (insert-buffer-substring cur)
4794     (mime-to-mml)
4795     (message-narrow-to-head-1)
4796     ;; Remove unwanted headers.
4797     (when message-ignored-supersedes-headers
4798       (message-remove-header message-ignored-supersedes-headers t))
4799     (goto-char (point-min))
4800     (if (not (re-search-forward "^Message-ID: " nil t))
4801         (error "No Message-ID in this article")
4802       (replace-match "Supersedes: " t t))
4803     (goto-char (point-max))
4804     (insert mail-header-separator)
4805     (widen)
4806     (forward-line 1)))
4807
4808 ;;;###autoload
4809 (defun message-recover ()
4810   "Reread contents of current buffer from its last auto-save file."
4811   (interactive)
4812   (let ((file-name (make-auto-save-file-name)))
4813     (cond ((save-window-excursion
4814              (if (not (eq system-type 'vax-vms))
4815                  (with-output-to-temp-buffer "*Directory*"
4816                    (with-current-buffer standard-output
4817                      (fundamental-mode)) ; for Emacs 20.4+
4818                    (buffer-disable-undo standard-output)
4819                    (let ((default-directory "/"))
4820                      (call-process
4821                       "ls" nil standard-output nil "-l" file-name))))
4822              (yes-or-no-p (format "Recover auto save file %s? " file-name)))
4823            (let ((buffer-read-only nil))
4824              (erase-buffer)
4825              (insert-file-contents file-name nil)))
4826           (t (error "message-recover cancelled")))))
4827
4828 ;;; Washing Subject:
4829
4830 (defun message-wash-subject (subject)
4831   "Remove junk like \"Re:\", \"(fwd)\", etc. added to subject string SUBJECT.
4832 Previous forwarders, replyers, etc. may add it."
4833   (with-temp-buffer
4834     (insert subject)
4835     (goto-char (point-min))
4836     ;; strip Re/Fwd stuff off the beginning
4837     (while (re-search-forward
4838             "\\([Rr][Ee]:\\|[Ff][Ww][Dd]\\(\\[[0-9]*\\]\\)?:\\|[Ff][Ww]:\\)" nil t)
4839       (replace-match ""))
4840
4841     ;; and gnus-style forwards [foo@bar.com] subject
4842     (goto-char (point-min))
4843     (while (re-search-forward "\\[[^ \t]*\\(@\\|\\.\\)[^ \t]*\\]" nil t)
4844       (replace-match ""))
4845
4846     ;; and off the end
4847     (goto-char (point-max))
4848     (while (re-search-backward "([Ff][Ww][Dd])" nil t)
4849       (replace-match ""))
4850
4851     ;; and finally, any whitespace that was left-over
4852     (goto-char (point-min))
4853     (while (re-search-forward "^[ \t]+" nil t)
4854       (replace-match ""))
4855     (goto-char (point-max))
4856     (while (re-search-backward "[ \t]+$" nil t)
4857       (replace-match ""))
4858
4859     (buffer-string)))
4860
4861 ;;; Forwarding messages.
4862
4863 (defvar message-forward-decoded-p nil
4864   "Non-nil means the original message is decoded.")
4865
4866 (defun message-forward-subject-author-subject (subject)
4867   "Generate a SUBJECT for a forwarded message.
4868 The form is: [Source] Subject, where if the original message was mail,
4869 Source is the sender, and if the original message was news, Source is
4870 the list of newsgroups is was posted to."
4871   (concat "["
4872           (let ((prefix
4873                  (or (message-fetch-field "newsgroups")
4874                      (message-fetch-field "from")
4875                      "(nowhere)")))
4876             (if message-forward-decoded-p
4877                 prefix
4878               (mail-decode-encoded-word-string prefix)))
4879           "] " subject))
4880
4881 (defun message-forward-subject-fwd (subject)
4882   "Generate a SUBJECT for a forwarded message.
4883 The form is: Fwd: Subject, where Subject is the original subject of
4884 the message."
4885   (concat "Fwd: " subject))
4886
4887 (defun message-make-forward-subject ()
4888   "Return a Subject header suitable for the message in the current buffer."
4889   (save-excursion
4890     (save-restriction
4891       (message-narrow-to-head-1)
4892       (let ((funcs message-make-forward-subject-function)
4893             (subject (message-fetch-field "Subject")))
4894         (setq subject
4895               (if subject
4896                   (if message-forward-decoded-p
4897                       subject
4898                     (mail-decode-encoded-word-string subject))
4899                 ""))
4900         (if message-wash-forwarded-subjects
4901             (setq subject (message-wash-subject subject)))
4902         ;; Make sure funcs is a list.
4903         (and funcs
4904              (not (listp funcs))
4905              (setq funcs (list funcs)))
4906         ;; Apply funcs in order, passing subject generated by previous
4907         ;; func to the next one.
4908         (while funcs
4909           (when (message-functionp (car funcs))
4910             (setq subject (funcall (car funcs) subject)))
4911           (setq funcs (cdr funcs)))
4912         subject))))
4913
4914 (eval-when-compile
4915   (defvar gnus-article-decoded-p))
4916
4917
4918 ;;;###autoload
4919 (defun message-forward (&optional news digest)
4920   "Forward the current message via mail.
4921 Optional NEWS will use news to forward instead of mail.
4922 Optional DIGEST will use digest to forward."
4923   (interactive "P")
4924   (let* ((cur (current-buffer))
4925          (message-forward-decoded-p
4926           (if (local-variable-p 'gnus-article-decoded-p (current-buffer))
4927               gnus-article-decoded-p ;; In an article buffer.
4928             message-forward-decoded-p))
4929          (subject (message-make-forward-subject)))
4930     (if news
4931         (message-news nil subject)
4932       (message-mail nil subject))
4933     (message-forward-make-body cur digest)))
4934
4935 ;;;###autoload
4936 (defun message-forward-make-body (forward-buffer &optional digest)
4937   ;; Put point where we want it before inserting the forwarded
4938   ;; message.
4939   (if message-forward-before-signature
4940       (message-goto-body)
4941     (goto-char (point-max)))
4942   (if message-forward-as-mime
4943       (if digest
4944           (insert "\n<#multipart type=digest>\n")
4945         (if message-forward-show-mml
4946             (insert "\n\n<#mml type=message/rfc822 disposition=inline>\n")
4947           (insert "\n\n<#part type=message/rfc822 disposition=inline raw=t>\n")))
4948     (insert "\n-------------------- Start of forwarded message --------------------\n"))
4949   (let ((b (point)) e)
4950     (if digest
4951         (if message-forward-as-mime
4952             (insert-buffer-substring forward-buffer)
4953           (mml-insert-buffer forward-buffer))
4954       (if (and message-forward-show-mml
4955                (not message-forward-decoded-p))
4956           (insert
4957            (with-temp-buffer
4958              (mm-disable-multibyte-mule4) ;; Must copy buffer in unibyte mode
4959                (insert
4960                 (with-current-buffer forward-buffer
4961                   (mm-string-as-unibyte (buffer-string))))
4962                (mm-enable-multibyte-mule4)
4963                (mime-to-mml)
4964                (goto-char (point-min))
4965                (when (looking-at "From ")
4966                  (replace-match "X-From-Line: "))
4967                (buffer-string)))
4968         (save-restriction
4969           (narrow-to-region (point) (point))
4970           (mml-insert-buffer forward-buffer)
4971           (goto-char (point-min))
4972           (when (looking-at "From ")
4973             (replace-match "X-From-Line: "))
4974           (goto-char (point-max)))))
4975     (setq e (point))
4976     (if message-forward-as-mime
4977         (if digest
4978             (insert "<#/multipart>\n")
4979           (if message-forward-show-mml
4980               (insert "<#/mml>\n")
4981             (insert "<#/part>\n")))
4982       (insert "\n-------------------- End of forwarded message --------------------\n"))
4983     (if (and digest message-forward-as-mime)
4984         (save-restriction
4985           (narrow-to-region b e)
4986           (goto-char b)
4987           (narrow-to-region (point)
4988                             (or (search-forward "\n\n" nil t) (point)))
4989           (delete-region (point-min) (point-max)))
4990       (when (and (not current-prefix-arg)
4991                  message-forward-ignored-headers)
4992         (save-restriction
4993           (narrow-to-region b e)
4994           (goto-char b)
4995           (narrow-to-region (point)
4996                             (or (search-forward "\n\n" nil t) (point)))
4997           (message-remove-header message-forward-ignored-headers t)))))
4998   (message-position-point))
4999
5000 ;;;###autoload
5001 (defun message-forward-rmail-make-body (forward-buffer)
5002   (save-window-excursion
5003     (set-buffer forward-buffer)
5004     (let (rmail-enable-mime)
5005       (rmail-toggle-header 0)))
5006   (message-forward-make-body forward-buffer))
5007
5008 ;;;###autoload
5009 (defun message-insinuate-rmail ()
5010   "Let RMAIL uses message to forward."
5011   (interactive)
5012   (setq rmail-enable-mime-composing t)
5013   (setq rmail-insert-mime-forwarded-message-function 
5014         'message-forward-rmail-make-body))
5015
5016 ;;;###autoload
5017 (defun message-resend (address)
5018   "Resend the current article to ADDRESS."
5019   (interactive
5020    (list (message-read-from-minibuffer "Resend message to: ")))
5021   (message "Resending message to %s..." address)
5022   (save-excursion
5023     (let ((cur (current-buffer))
5024           beg)
5025       ;; We first set up a normal mail buffer.
5026       (unless (message-mail-user-agent)
5027         (set-buffer (get-buffer-create " *message resend*"))
5028         (erase-buffer))
5029       (let ((message-this-is-mail t))
5030         (message-setup `((To . ,address))))
5031       ;; Insert our usual headers.
5032       (message-generate-headers '(From Date To))
5033       (message-narrow-to-headers)
5034       ;; Rename them all to "Resent-*".
5035       (while (re-search-forward "^[A-Za-z]" nil t)
5036         (forward-char -1)
5037         (insert "Resent-"))
5038       (widen)
5039       (forward-line)
5040       (delete-region (point) (point-max))
5041       (setq beg (point))
5042       ;; Insert the message to be resent.
5043       (insert-buffer-substring cur)
5044       (goto-char (point-min))
5045       (search-forward "\n\n")
5046       (forward-char -1)
5047       (save-restriction
5048         (narrow-to-region beg (point))
5049         (message-remove-header message-ignored-resent-headers t)
5050         (goto-char (point-max)))
5051       (insert mail-header-separator)
5052       ;; Rename all old ("Also-")Resent headers.
5053       (while (re-search-backward "^\\(Also-\\)*Resent-" beg t)
5054         (beginning-of-line)
5055         (insert "Also-"))
5056       ;; Quote any "From " lines at the beginning.
5057       (goto-char beg)
5058       (when (looking-at "From ")
5059         (replace-match "X-From-Line: "))
5060       ;; Send it.
5061       (let ((message-inhibit-body-encoding t)
5062             message-required-mail-headers)
5063         (message-send-mail))
5064       (kill-buffer (current-buffer)))
5065     (message "Resending message to %s...done" address)))
5066
5067 ;;;###autoload
5068 (defun message-bounce ()
5069   "Re-mail the current message.
5070 This only makes sense if the current message is a bounce message that
5071 contains some mail you have written which has been bounced back to
5072 you."
5073   (interactive)
5074   (let ((handles (mm-dissect-buffer t))
5075         boundary)
5076     (message-pop-to-buffer (message-buffer-name "bounce"))
5077     (if (stringp (car handles))
5078         ;; This is a MIME bounce.
5079         (mm-insert-part (car (last handles)))
5080       ;; This is a non-MIME bounce, so we try to remove things
5081       ;; manually.
5082       (mm-insert-part handles)
5083       (undo-boundary)
5084       (goto-char (point-min))
5085       (search-forward "\n\n" nil t)
5086       (if (or (and (re-search-forward message-unsent-separator nil t)
5087                    (forward-line 1))
5088               (re-search-forward "^Return-Path:.*\n" nil t))
5089           ;; We remove everything before the bounced mail.
5090           (delete-region
5091            (point-min)
5092            (if (re-search-forward "^[^ \n\t]+:" nil t)
5093                (match-beginning 0)
5094              (point)))
5095         (when (re-search-backward "^.?From .*\n" nil t)
5096           (delete-region (match-beginning 0) (match-end 0)))))
5097     (mm-enable-multibyte)
5098     (mime-to-mml)
5099     (save-restriction
5100       (message-narrow-to-head-1)
5101       (message-remove-header message-ignored-bounced-headers t)
5102       (goto-char (point-max))
5103       (insert mail-header-separator))
5104     (message-position-point)))
5105
5106 ;;;
5107 ;;; Interactive entry points for new message buffers.
5108 ;;;
5109
5110 ;;;###autoload
5111 (defun message-mail-other-window (&optional to subject)
5112   "Like `message-mail' command, but display mail buffer in another window."
5113   (interactive)
5114   (unless (message-mail-user-agent)
5115     (let ((pop-up-windows t)
5116           (special-display-buffer-names nil)
5117           (special-display-regexps nil)
5118           (same-window-buffer-names nil)
5119           (same-window-regexps nil))
5120       (message-pop-to-buffer (message-buffer-name "mail" to))))
5121   (let ((message-this-is-mail t))
5122     (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))
5123                    nil nil 'switch-to-buffer-other-window)))
5124
5125 ;;;###autoload
5126 (defun message-mail-other-frame (&optional to subject)
5127   "Like `message-mail' command, but display mail buffer in another frame."
5128   (interactive)
5129   (unless (message-mail-user-agent)
5130     (let ((pop-up-frames t)
5131           (special-display-buffer-names nil)
5132           (special-display-regexps nil)
5133           (same-window-buffer-names nil)
5134           (same-window-regexps nil))
5135       (message-pop-to-buffer (message-buffer-name "mail" to))))
5136   (let ((message-this-is-mail t))
5137     (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))
5138                    nil nil 'switch-to-buffer-other-frame)))
5139
5140 ;;;###autoload
5141 (defun message-news-other-window (&optional newsgroups subject)
5142   "Start editing a news article to be sent."
5143   (interactive)
5144   (let ((pop-up-windows t)
5145         (special-display-buffer-names nil)
5146         (special-display-regexps nil)
5147         (same-window-buffer-names nil)
5148         (same-window-regexps nil))
5149     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups)))
5150   (let ((message-this-is-news t))
5151     (message-setup `((Newsgroups . ,(or newsgroups ""))
5152                      (Subject . ,(or subject ""))))))
5153
5154 ;;;###autoload
5155 (defun message-news-other-frame (&optional newsgroups subject)
5156   "Start editing a news article to be sent."
5157   (interactive)
5158   (let ((pop-up-frames t)
5159         (special-display-buffer-names nil)
5160         (special-display-regexps nil)
5161         (same-window-buffer-names nil)
5162         (same-window-regexps nil))
5163     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups)))
5164   (let ((message-this-is-news t))
5165     (message-setup `((Newsgroups . ,(or newsgroups ""))
5166                      (Subject . ,(or subject ""))))))
5167
5168 ;;; underline.el
5169
5170 ;; This code should be moved to underline.el (from which it is stolen).
5171
5172 ;;;###autoload
5173 (defun bold-region (start end)
5174   "Bold all nonblank characters in the region.
5175 Works by overstriking characters.
5176 Called from program, takes two arguments START and END
5177 which specify the range to operate on."
5178   (interactive "r")
5179   (save-excursion
5180     (let ((end1 (make-marker)))
5181       (move-marker end1 (max start end))
5182       (goto-char (min start end))
5183       (while (< (point) end1)
5184         (or (looking-at "[_\^@- ]")
5185             (insert (char-after) "\b"))
5186         (forward-char 1)))))
5187
5188 ;;;###autoload
5189 (defun unbold-region (start end)
5190   "Remove all boldness (overstruck characters) in the region.
5191 Called from program, takes two arguments START and END
5192 which specify the range to operate on."
5193   (interactive "r")
5194   (save-excursion
5195     (let ((end1 (make-marker)))
5196       (move-marker end1 (max start end))
5197       (goto-char (min start end))
5198       (while (re-search-forward "\b" end1 t)
5199         (if (eq (char-after) (char-after (- (point) 2)))
5200             (delete-char -2))))))
5201
5202 (defalias 'message-exchange-point-and-mark 'exchange-point-and-mark)
5203
5204 ;; Support for toolbar
5205 (eval-when-compile
5206   (defvar tool-bar-map)
5207   (defvar tool-bar-mode))
5208
5209 (defun message-tool-bar-map ()
5210   (or message-tool-bar-map
5211       (setq message-tool-bar-map
5212             (and (fboundp 'tool-bar-add-item-from-menu)
5213                  tool-bar-mode
5214                  (let ((tool-bar-map (copy-keymap tool-bar-map))
5215                        (load-path (mm-image-load-path)))
5216                    ;; Zap some items which aren't so relevant and take
5217                    ;; up space.
5218                    (dolist (key '(print-buffer kill-buffer save-buffer
5219                                                write-file dired open-file))
5220                      (define-key tool-bar-map (vector key) nil))
5221                    (tool-bar-add-item-from-menu
5222                     'message-send-and-exit "mail_send" message-mode-map)
5223                    (tool-bar-add-item-from-menu
5224                     'message-kill-buffer "close" message-mode-map)
5225                    (tool-bar-add-item-from-menu
5226                     'message-dont-send "cancel" message-mode-map)
5227                    (tool-bar-add-item-from-menu
5228                     'mml-attach-file "attach" mml-mode-map)
5229                    (tool-bar-add-item-from-menu
5230                     'ispell-message "spell" message-mode-map)
5231                    (tool-bar-add-item-from-menu
5232                     'message-insert-importance-high "important"
5233                     message-mode-map)
5234                    (tool-bar-add-item-from-menu
5235                     'message-insert-importance-low "unimportant"
5236                     message-mode-map)
5237                    (tool-bar-add-item-from-menu
5238                     'message-insert-disposition-notification-to "receipt"
5239                     message-mode-map)
5240                    tool-bar-map)))))
5241
5242 ;;; Group name completion.
5243
5244 (defcustom message-newgroups-header-regexp
5245   "^\\(Newsgroups\\|Followup-To\\|Posted-To\\|Gcc\\):"
5246   "Regexp that match headers that lists groups."
5247   :group 'message
5248   :type 'regexp)
5249
5250 (defcustom message-completion-alist
5251   (list (cons message-newgroups-header-regexp 'message-expand-group)
5252         '("^\\(Resent-\\)?\\(To\\|B?Cc\\):" . message-expand-name))
5253   "Alist of (RE . FUN).  Use FUN for completion on header lines matching RE."
5254   :group 'message
5255   :type '(alist :key-type regexp :value-type function))
5256
5257 (defcustom message-tab-body-function nil
5258   "*Function to execute when `message-tab' (TAB) is executed in the body.
5259 If nil, the function bound in `text-mode-map' or `global-map' is executed."
5260   :group 'message
5261   :type 'function)
5262
5263 (defun message-tab ()
5264   "Complete names according to `message-completion-alist'.
5265 Execute function specified by `message-tab-body-function' when not in
5266 those headers."
5267   (interactive)
5268   (let ((alist message-completion-alist))
5269     (while (and alist
5270                 (let ((mail-abbrev-mode-regexp (caar alist)))
5271                   (not (mail-abbrev-in-expansion-header-p))))
5272       (setq alist (cdr alist)))
5273     (funcall (or (cdar alist) message-tab-body-function
5274                  (lookup-key text-mode-map "\t")
5275                  (lookup-key global-map "\t")
5276                  'indent-relative))))
5277
5278 (defun message-expand-group ()
5279   "Expand the group name under point."
5280   (let* ((b (save-excursion
5281               (save-restriction
5282                 (narrow-to-region
5283                  (save-excursion
5284                    (beginning-of-line)
5285                    (skip-chars-forward "^:")
5286                    (1+ (point)))
5287                  (point))
5288                 (skip-chars-backward "^, \t\n") (point))))
5289          (completion-ignore-case t)
5290          (string (buffer-substring b (progn (skip-chars-forward "^,\t\n ")
5291                                             (point))))
5292          (hashtb (and (boundp 'gnus-active-hashtb) gnus-active-hashtb))
5293          (completions (all-completions string hashtb))
5294          comp)
5295     (delete-region b (point))
5296     (cond
5297      ((= (length completions) 1)
5298       (if (string= (car completions) string)
5299           (progn
5300             (insert string)
5301             (message "Only matching group"))
5302         (insert (car completions))))
5303      ((and (setq comp (try-completion string hashtb))
5304            (not (string= comp string)))
5305       (insert comp))
5306      (t
5307       (insert string)
5308       (if (not comp)
5309           (message "No matching groups")
5310         (save-selected-window
5311           (pop-to-buffer "*Completions*")
5312           (buffer-disable-undo)
5313           (let ((buffer-read-only nil))
5314             (erase-buffer)
5315             (let ((standard-output (current-buffer)))
5316               (display-completion-list (sort completions 'string<)))
5317             (goto-char (point-min))
5318             (delete-region (point) (progn (forward-line 3) (point))))))))))
5319
5320 (defun message-expand-name ()
5321   (if (fboundp 'bbdb-complete-name)
5322       (bbdb-complete-name)
5323     (expand-abbrev)))
5324
5325 ;;; Help stuff.
5326
5327 (defun message-talkative-question (ask question show &rest text)
5328   "Call FUNCTION with argument QUESTION; optionally display TEXT... args.
5329 If SHOW is non-nil, the arguments TEXT... are displayed in a temp buffer.
5330 The following arguments may contain lists of values."
5331   (if (and show
5332            (setq text (message-flatten-list text)))
5333       (save-window-excursion
5334         (save-excursion
5335           (with-output-to-temp-buffer " *MESSAGE information message*"
5336             (set-buffer " *MESSAGE information message*")
5337             (fundamental-mode)          ; for Emacs 20.4+
5338             (mapcar 'princ text)
5339             (goto-char (point-min))))
5340         (funcall ask question))
5341     (funcall ask question)))
5342
5343 (defun message-flatten-list (list)
5344   "Return a new, flat list that contains all elements of LIST.
5345
5346 \(message-flatten-list '(1 (2 3 (4 5 (6))) 7))
5347 => (1 2 3 4 5 6 7)"
5348   (cond ((consp list)
5349          (apply 'append (mapcar 'message-flatten-list list)))
5350         (list
5351          (list list))))
5352
5353 (defun message-generate-new-buffer-clone-locals (name &optional varstr)
5354   "Create and return a buffer with name based on NAME using `generate-new-buffer.'
5355 Then clone the local variables and values from the old buffer to the
5356 new one, cloning only the locals having a substring matching the
5357 regexp varstr."
5358   (let ((oldbuf (current-buffer)))
5359     (save-excursion
5360       (set-buffer (generate-new-buffer name))
5361       (message-clone-locals oldbuf varstr)
5362       (current-buffer))))
5363
5364 (defun message-clone-locals (buffer &optional varstr)
5365   "Clone the local variables from BUFFER to the current buffer."
5366   (let ((locals (save-excursion
5367                   (set-buffer buffer)
5368                   (buffer-local-variables)))
5369         (regexp "^gnus\\|^nn\\|^message\\|^user-mail-address"))
5370     (mapcar
5371      (lambda (local)
5372        (when (and (consp local)
5373                   (car local)
5374                   (string-match regexp (symbol-name (car local)))
5375                   (or (null varstr)
5376                       (string-match varstr (symbol-name (car local)))))
5377          (ignore-errors
5378            (set (make-local-variable (car local))
5379                 (cdr local)))))
5380      locals)))
5381
5382 ;;; Miscellaneous functions
5383
5384 (defsubst message-replace-chars-in-string (string from to)
5385   (mm-subst-char-in-string from to string))
5386
5387 ;;;
5388 ;;; MIME functions
5389 ;;;
5390
5391 (defvar message-inhibit-body-encoding nil)
5392
5393 (defun message-encode-message-body ()
5394   (unless message-inhibit-body-encoding
5395     (let ((mail-parse-charset (or mail-parse-charset
5396                                   message-default-charset))
5397           (case-fold-search t)
5398           lines content-type-p)
5399       (message-goto-body)
5400       (save-restriction
5401         (narrow-to-region (point) (point-max))
5402         (let ((new (mml-generate-mime)))
5403           (when new
5404             (delete-region (point-min) (point-max))
5405             (insert new)
5406             (goto-char (point-min))
5407             (if (eq (aref new 0) ?\n)
5408                 (delete-char 1)
5409               (search-forward "\n\n")
5410               (setq lines (buffer-substring (point-min) (1- (point))))
5411               (delete-region (point-min) (point))))))
5412       (save-restriction
5413         (message-narrow-to-headers-or-head)
5414         (message-remove-header "Mime-Version")
5415         (goto-char (point-max))
5416         (insert "MIME-Version: 1.0\n")
5417         (when lines
5418           (insert lines))
5419         (setq content-type-p
5420               (or mml-boundary
5421                   (re-search-backward "^Content-Type:" nil t))))
5422       (save-restriction
5423         (message-narrow-to-headers-or-head)
5424         (message-remove-first-header "Content-Type")
5425         (message-remove-first-header "Content-Transfer-Encoding"))
5426       ;; We always make sure that the message has a Content-Type
5427       ;; header.  This is because some broken MTAs and MUAs get
5428       ;; awfully confused when confronted with a message with a
5429       ;; MIME-Version header and without a Content-Type header.  For
5430       ;; instance, Solaris' /usr/bin/mail.
5431       (unless content-type-p
5432         (goto-char (point-min))
5433         ;; For unknown reason, MIME-Version doesn't exist.
5434         (when (re-search-forward "^MIME-Version:" nil t)
5435           (forward-line 1)
5436           (insert "Content-Type: text/plain; charset=us-ascii\n"))))))
5437
5438 (defun message-read-from-minibuffer (prompt &optional initial-contents)
5439   "Read from the minibuffer while providing abbrev expansion."
5440   (if (fboundp 'mail-abbrevs-setup)
5441       (let ((mail-abbrev-mode-regexp "")
5442             (minibuffer-setup-hook 'mail-abbrevs-setup)
5443             (minibuffer-local-map message-minibuffer-local-map))
5444         (read-from-minibuffer prompt initial-contents))
5445     (let ((minibuffer-setup-hook 'mail-abbrev-minibuffer-setup-hook)
5446           (minibuffer-local-map message-minibuffer-local-map))
5447       (read-string prompt initial-contents))))
5448
5449 (defun message-use-alternative-email-as-from ()
5450   (require 'mail-utils)
5451   (let* ((fields '("To" "Cc"))
5452          (emails
5453           (split-string
5454            (mail-strip-quoted-names
5455             (mapconcat 'message-fetch-reply-field fields ","))
5456            "[ \f\t\n\r\v,]+"))
5457          email)
5458     (while emails
5459       (if (string-match message-alternative-emails (car emails))
5460           (setq email (car emails)
5461                 emails nil))
5462       (pop emails))
5463     (unless (or (not email) (equal email user-mail-address))
5464       (goto-char (point-max))
5465       (insert "From: " email "\n"))))
5466
5467 (defun message-options-get (symbol)
5468   (cdr (assq symbol message-options)))
5469
5470 (defun message-options-set (symbol value)
5471   (let ((the-cons (assq symbol message-options)))
5472     (if the-cons
5473         (if value
5474             (setcdr the-cons value)
5475           (setq message-options (delq the-cons message-options)))
5476       (and value
5477            (push (cons symbol value) message-options))))
5478   value)
5479
5480 (defun message-options-set-recipient ()
5481   (save-restriction
5482     (message-narrow-to-headers-or-head)
5483     (message-options-set 'message-sender
5484                          (mail-strip-quoted-names
5485                           (message-fetch-field "from")))
5486     (message-options-set 'message-recipients
5487                          (mail-strip-quoted-names
5488                           (let ((to (message-fetch-field "to"))
5489                                 (cc (message-fetch-field "cc"))
5490                                 (bcc (message-fetch-field "bcc")))
5491                             (concat
5492                              (or to "")
5493                              (if (and to cc) ", ")
5494                              (or cc "")
5495                              (if (and (or to cc) bcc) ", ")
5496                              (or bcc "")))))))
5497
5498 (when (featurep 'xemacs)
5499   (require 'messagexmas)
5500   (message-xmas-redefine))
5501
5502 (provide 'message)
5503
5504 (run-hooks 'message-load-hook)
5505
5506 ;; Local Variables:
5507 ;; coding: iso-8859-1
5508 ;; End:
5509
5510 ;;; message.el ends here