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