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