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