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