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