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