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