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