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