fed132eab97f399d0a043cbc2492d7dc85032590
[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.landfield.com/usefor/drafts/draft-ietf-usefor-useage--1.02.unpaged>
1919   (interactive
1920    (list
1921     (read-from-minibuffer "New subject: ")))
1922   (cond ((and (not (or (null new-subject) ; new subject not empty
1923                        (zerop (string-width new-subject))
1924                        (string-match "^[ \t]*$" new-subject))))
1925          (save-excursion
1926            (let ((old-subject
1927                   (save-restriction
1928                     (message-narrow-to-headers)
1929                     (message-fetch-field "Subject"))))
1930              (cond ((not old-subject)
1931                     (error "No current subject"))
1932                    ((not (string-match
1933                           (concat "^[ \t]*"
1934                                   (regexp-quote new-subject)
1935                                   " \t]*$")
1936                           old-subject))  ; yes, it really is a new subject
1937                     ;; delete eventual Re: prefix
1938                     (setq old-subject
1939                           (message-strip-subject-re old-subject))
1940                     (message-goto-subject)
1941                     (message-delete-line)
1942                     (insert (concat "Subject: "
1943                                     new-subject
1944                                     " (was: "
1945                                     old-subject ")\n")))))))))
1946
1947 ;;;###autoload
1948 (defun message-mark-inserted-region (beg end)
1949   "Mark some region in the current article with enclosing tags.
1950 See `message-mark-insert-begin' and `message-mark-insert-end'."
1951   (interactive "r")
1952   (save-excursion
1953     ;; add to the end of the region first, otherwise end would be invalid
1954     (goto-char end)
1955     (insert message-mark-insert-end)
1956     (goto-char beg)
1957     (insert message-mark-insert-begin)))
1958
1959 ;;;###autoload
1960 (defun message-mark-insert-file (file)
1961   "Insert FILE at point, marking it with enclosing tags.
1962 See `message-mark-insert-begin' and `message-mark-insert-end'."
1963   (interactive "fFile to insert: ")
1964     ;; reverse insertion to get correct result.
1965   (let ((p (point)))
1966     (insert message-mark-insert-end)
1967     (goto-char p)
1968     (insert-file-contents file)
1969     (goto-char p)
1970     (insert message-mark-insert-begin)))
1971
1972 ;;;###autoload
1973 (defun message-add-archive-header ()
1974   "Insert \"X-No-Archive: Yes\" in the header and a note in the body.
1975 The note can be customized using `message-archive-note'.  When called with a
1976 prefix argument, ask for a text to insert.  If you don't want the note in the
1977 body, set  `message-archive-note' to nil."
1978   (interactive)
1979   (if current-prefix-arg
1980       (setq message-archive-note
1981             (read-from-minibuffer "Reason for No-Archive: "
1982                                   (cons message-archive-note 0))))
1983     (save-excursion
1984       (if (message-goto-signature)
1985           (re-search-backward message-signature-separator))
1986       (when message-archive-note
1987         (insert message-archive-note)
1988         (newline))
1989       (message-add-header message-archive-header)
1990       (message-sort-headers)))
1991
1992 ;;;###autoload
1993 (defun message-cross-post-followup-to-header (target-group)
1994   "Mangles FollowUp-To and Newsgroups header to point to TARGET-GROUP.
1995 With prefix-argument just set Follow-Up, don't cross-post."
1996   (interactive
1997    (list ; Completion based on Gnus
1998     (completing-read "Followup To: "
1999                      (if (boundp 'gnus-newsrc-alist)
2000                          gnus-newsrc-alist)
2001                      nil nil '("poster" . 0)
2002                      (if (boundp 'gnus-group-history)
2003                          'gnus-group-history))))
2004   (message-remove-header "Follow[Uu]p-[Tt]o" t)
2005   (message-goto-newsgroups)
2006   (beginning-of-line)
2007   ;; if we already did a crosspost before, kill old target
2008   (if (and message-cross-post-old-target
2009            (re-search-forward
2010             (regexp-quote (concat "," message-cross-post-old-target))
2011             nil t))
2012       (replace-match ""))
2013   ;; unless (followup is to poster or user explicitly asked not
2014   ;; to cross-post, or target-group is already in Newsgroups)
2015   ;; add target-group to Newsgroups line.
2016   (cond ((and (or
2017                ;; def: cross-post, req:no
2018                (and message-cross-post-default (not current-prefix-arg))
2019                ;; def: no-cross-post, req:yes
2020                (and (not message-cross-post-default) current-prefix-arg))
2021               (not (string-match "poster" target-group))
2022               (not (string-match (regexp-quote target-group)
2023                                  (message-fetch-field "Newsgroups"))))
2024          (end-of-line)
2025          (insert (concat "," target-group))))
2026   (end-of-line) ; ensure Followup: comes after Newsgroups:
2027   ;; unless new followup would be identical to Newsgroups line
2028   ;; make a new Followup-To line
2029   (if (not (string-match (concat "^[ \t]*"
2030                                  target-group
2031                                  "[ \t]*$")
2032                          (message-fetch-field "Newsgroups")))
2033       (insert (concat "\nFollowup-To: " target-group)))
2034   (setq message-cross-post-old-target target-group))
2035
2036 ;;;###autoload
2037 (defun message-cross-post-insert-note (target-group cross-post in-old
2038                                                     old-groups)
2039   "Insert a in message body note about a set Followup or Crosspost.
2040 If there have been previous notes, delete them.  TARGET-GROUP specifies the
2041 group to Followup-To.  When CROSS-POST is t, insert note about
2042 crossposting.  IN-OLD specifies whether TARGET-GROUP is a member of
2043 OLD-GROUPS.  OLD-GROUPS lists the old-groups the posting would have
2044 been made to before the user asked for a Crosspost."
2045   ;; start scanning body for previous uses
2046   (message-goto-signature)
2047   (let ((head (re-search-backward
2048                (concat "^" mail-header-separator)
2049                nil t))) ; just search in body
2050     (message-goto-signature)
2051     (while (re-search-backward
2052             (concat "^" (regexp-quote message-cross-post-note) ".*")
2053             head t)
2054       (message-delete-line))
2055     (message-goto-signature)
2056     (while (re-search-backward
2057             (concat "^" (regexp-quote message-followup-to-note) ".*")
2058             head t)
2059       (message-delete-line))
2060     ;; insert new note
2061     (if (message-goto-signature)
2062         (re-search-backward message-signature-separator))
2063     (if (or in-old
2064             (not cross-post)
2065             (string-match "^[ \t]*poster[ \t]*$" target-group))
2066         (insert (concat message-followup-to-note target-group "\n"))
2067       (insert (concat message-cross-post-note target-group "\n")))))
2068
2069 ;;;###autoload
2070 (defun message-cross-post-followup-to (target-group)
2071   "Crossposts message and set Followup-To to TARGET-GROUP.
2072 With prefix-argument just set Follow-Up, don't cross-post."
2073   (interactive
2074    (list ; Completion based on Gnus
2075     (completing-read "Followup To: "
2076                      (if (boundp 'gnus-newsrc-alist)
2077                          gnus-newsrc-alist)
2078                      nil nil '("poster" . 0)
2079                      (if (boundp 'gnus-group-history)
2080                          'gnus-group-history))))
2081   (cond ((not (or (null target-group) ; new subject not empty
2082                   (zerop (string-width target-group))
2083                   (string-match "^[ \t]*$" target-group)))
2084          (save-excursion
2085            (let* ((old-groups (message-fetch-field "Newsgroups"))
2086                   (in-old (string-match
2087                            (regexp-quote target-group)
2088                            (or old-groups ""))))
2089              ;; check whether target exactly matches old Newsgroups
2090              (cond ((not old-groups)
2091                     (error "No current newsgroup"))
2092                    ((or (not in-old)
2093                         (not (string-match
2094                               (concat "^[ \t]*"
2095                                       (regexp-quote target-group)
2096                                       "[ \t]*$")
2097                               old-groups)))
2098                     ;; yes, Newsgroups line must change
2099                     (message-cross-post-followup-to-header target-group)
2100                     ;; insert note whether we do cross-post or followup-to
2101                     (funcall message-cross-post-note-function
2102                              target-group
2103                              (if (or (and message-cross-post-default
2104                                           (not current-prefix-arg))
2105                                      (and (not message-cross-post-default)
2106                                           current-prefix-arg)) t)
2107                              in-old old-groups))))))))
2108
2109 ;;; Reduce To: to Cc: or Bcc: header
2110
2111 ;;;###autoload
2112 (defun message-reduce-to-to-cc ()
2113  "Replace contents of To: header with contents of Cc: or Bcc: header."
2114  (interactive)
2115  (let ((cc-content
2116         (save-restriction (message-narrow-to-headers)
2117                           (message-fetch-field "cc")))
2118        (bcc nil))
2119    (if (and (not cc-content)
2120             (setq cc-content
2121                   (save-restriction
2122                     (message-narrow-to-headers)
2123                     (message-fetch-field "bcc"))))
2124        (setq bcc t))
2125    (cond (cc-content
2126           (save-excursion
2127             (message-goto-to)
2128             (message-delete-line)
2129             (insert (concat "To: " cc-content "\n"))
2130             (save-restriction
2131               (message-narrow-to-headers)
2132               (message-remove-header (if bcc
2133                                          "bcc"
2134                                        "cc"))))))))
2135
2136 ;;; End of functions adopted from `message-utils.el'.
2137
2138 (defun message-remove-header (header &optional is-regexp first reverse)
2139   "Remove HEADER in the narrowed buffer.
2140 If IS-REGEXP, HEADER is a regular expression.
2141 If FIRST, only remove the first instance of the header.
2142 Return the number of headers removed."
2143   (goto-char (point-min))
2144   (let ((regexp (if is-regexp header (concat "^" (regexp-quote header) ":")))
2145         (number 0)
2146         (case-fold-search t)
2147         last)
2148     (while (and (not (eobp))
2149                 (not last))
2150       (if (if reverse
2151               (not (looking-at regexp))
2152             (looking-at regexp))
2153           (progn
2154             (incf number)
2155             (when first
2156               (setq last t))
2157             (delete-region
2158              (point)
2159              ;; There might be a continuation header, so we have to search
2160              ;; until we find a new non-continuation line.
2161              (progn
2162                (forward-line 1)
2163                (if (re-search-forward "^[^ \t]" nil t)
2164                    (goto-char (match-beginning 0))
2165                  (point-max)))))
2166         (forward-line 1)
2167         (if (re-search-forward "^[^ \t]" nil t)
2168             (goto-char (match-beginning 0))
2169           (goto-char (point-max)))))
2170     number))
2171
2172 (defun message-remove-first-header (header)
2173   "Remove the first instance of HEADER if there is more than one."
2174   (let ((count 0)
2175         (regexp (concat "^" (regexp-quote header) ":")))
2176     (save-excursion
2177       (goto-char (point-min))
2178       (while (re-search-forward regexp nil t)
2179         (incf count)))
2180     (while (> count 1)
2181       (message-remove-header header nil t)
2182       (decf count))))
2183
2184 (defun message-narrow-to-headers ()
2185   "Narrow the buffer to the head of the message."
2186   (widen)
2187   (narrow-to-region
2188    (goto-char (point-min))
2189    (if (re-search-forward
2190         (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
2191        (match-beginning 0)
2192      (point-max)))
2193   (goto-char (point-min)))
2194
2195 (defun message-narrow-to-head-1 ()
2196   "Like `message-narrow-to-head'.  Don't widen."
2197   (narrow-to-region
2198    (goto-char (point-min))
2199    (if (search-forward "\n\n" nil 1)
2200        (1- (point))
2201      (point-max)))
2202   (goto-char (point-min)))
2203
2204 (defun message-narrow-to-head ()
2205   "Narrow the buffer to the head of the message.
2206 Point is left at the beginning of the narrowed-to region."
2207   (widen)
2208   (message-narrow-to-head-1))
2209
2210 (defun message-narrow-to-headers-or-head ()
2211   "Narrow the buffer to the head of the message."
2212   (widen)
2213   (narrow-to-region
2214    (goto-char (point-min))
2215    (cond
2216     ((re-search-forward
2217       (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
2218      (match-beginning 0))
2219     ((search-forward "\n\n" nil t)
2220      (1- (point)))
2221     (t
2222      (point-max))))
2223   (goto-char (point-min)))
2224
2225 (defun message-news-p ()
2226   "Say whether the current buffer contains a news message."
2227   (and (not message-this-is-mail)
2228        (or message-this-is-news
2229            (save-excursion
2230              (save-restriction
2231                (message-narrow-to-headers)
2232                (and (message-fetch-field "newsgroups")
2233                     (not (message-fetch-field "posted-to"))))))))
2234
2235 (defun message-mail-p ()
2236   "Say whether the current buffer contains a mail message."
2237   (and (not message-this-is-news)
2238        (or message-this-is-mail
2239            (save-excursion
2240              (save-restriction
2241                (message-narrow-to-headers)
2242                (or (message-fetch-field "to")
2243                    (message-fetch-field "cc")
2244                    (message-fetch-field "bcc")))))))
2245
2246 (defun message-subscribed-p ()
2247   "Say whether we need to insert a MFT header."
2248   (or message-subscribed-regexps
2249       message-subscribed-addresses
2250       message-subscribed-address-file
2251       message-subscribed-address-functions))
2252
2253 (defun message-next-header ()
2254   "Go to the beginning of the next header."
2255   (beginning-of-line)
2256   (or (eobp) (forward-char 1))
2257   (not (if (re-search-forward "^[^ \t]" nil t)
2258            (beginning-of-line)
2259          (goto-char (point-max)))))
2260
2261 (defun message-sort-headers-1 ()
2262   "Sort the buffer as headers using `message-rank' text props."
2263   (goto-char (point-min))
2264   (require 'sort)
2265   (sort-subr
2266    nil 'message-next-header
2267    (lambda ()
2268      (message-next-header)
2269      (unless (bobp)
2270        (forward-char -1)))
2271    (lambda ()
2272      (or (get-text-property (point) 'message-rank)
2273          10000))))
2274
2275 (defun message-sort-headers ()
2276   "Sort the headers of the current message according to `message-header-format-alist'."
2277   (interactive)
2278   (save-excursion
2279     (save-restriction
2280       (let ((max (1+ (length message-header-format-alist)))
2281             rank)
2282         (message-narrow-to-headers)
2283         (while (re-search-forward "^[^ \n]+:" nil t)
2284           (put-text-property
2285            (match-beginning 0) (1+ (match-beginning 0))
2286            'message-rank
2287            (if (setq rank (length (memq (assq (intern (buffer-substring
2288                                                        (match-beginning 0)
2289                                                        (1- (match-end 0))))
2290                                               message-header-format-alist)
2291                                         message-header-format-alist)))
2292                (- max rank)
2293              (1+ max)))))
2294       (message-sort-headers-1))))
2295
2296 \f
2297
2298 ;;;
2299 ;;; Message mode
2300 ;;;
2301
2302 ;;; Set up keymap.
2303
2304 (defvar message-mode-map nil)
2305
2306 (unless message-mode-map
2307   (setq message-mode-map (make-keymap))
2308   (set-keymap-parent message-mode-map text-mode-map)
2309   (define-key message-mode-map "\C-c?" 'describe-mode)
2310
2311   (define-key message-mode-map "\C-c\C-f\C-t" 'message-goto-to)
2312   (define-key message-mode-map "\C-c\C-f\C-o" 'message-goto-from)
2313   (define-key message-mode-map "\C-c\C-f\C-b" 'message-goto-bcc)
2314   (define-key message-mode-map "\C-c\C-f\C-w" 'message-goto-fcc)
2315   (define-key message-mode-map "\C-c\C-f\C-c" 'message-goto-cc)
2316   (define-key message-mode-map "\C-c\C-f\C-s" 'message-goto-subject)
2317   ;; (define-key message-mode-map "\C-c\C-f\C-r" 'message-goto-reply-to)
2318   (define-key message-mode-map "\C-c\C-f\C-r" 'message-goto-mail-reply-to)
2319   (define-key message-mode-map "\C-c\C-f\C-m" 'message-goto-mail-followup-to)
2320   (define-key message-mode-map "\C-c\C-f\C-n" 'message-goto-newsgroups)
2321   (define-key message-mode-map "\C-c\C-f\C-d" 'message-goto-distribution)
2322   (define-key message-mode-map "\C-c\C-f\C-f" 'message-goto-followup-to)
2323   (define-key message-mode-map "\C-c\C-f\C-m" 'message-goto-mail-followup-to)
2324   (define-key message-mode-map "\C-c\C-f\C-k" 'message-goto-keywords)
2325   (define-key message-mode-map "\C-c\C-f\C-u" 'message-goto-summary)
2326   (define-key message-mode-map "\C-c\C-f\C-i"
2327     'message-insert-or-toggle-importance)
2328   (define-key message-mode-map "\C-c\C-f\C-a"
2329     'message-generate-unsubscribed-mail-followup-to)
2330
2331   ;; modify headers (and insert notes in body)
2332   (define-key message-mode-map "\C-c\C-fs"    'message-change-subject)
2333   ;;
2334   (define-key message-mode-map "\C-c\C-fx"    'message-cross-post-followup-to)
2335   ;; prefix+message-cross-post-followup-to = same w/o cross-post
2336   (define-key message-mode-map "\C-c\C-ft"    'message-reduce-to-to-cc)
2337   (define-key message-mode-map "\C-c\C-fa"    'message-add-archive-header)
2338   ;; mark inserted text
2339   (define-key message-mode-map "\C-c\M-m" 'message-mark-inserted-region)
2340   (define-key message-mode-map "\C-c\M-f" 'message-mark-insert-file)
2341
2342   (define-key message-mode-map "\C-c\C-b" 'message-goto-body)
2343   (define-key message-mode-map "\C-c\C-i" 'message-goto-signature)
2344   (define-key message-mode-map "\C-c\C-fc" 'message-goto-mail-copies-to)
2345
2346   (define-key message-mode-map "\C-c\C-t" 'message-insert-to)
2347   (define-key message-mode-map "\C-c\C-fw" 'message-insert-wide-reply)
2348   (define-key message-mode-map "\C-c\C-n" 'message-insert-newsgroups)
2349   (define-key message-mode-map "\C-c\C-l" 'message-to-list-only)
2350
2351   (define-key message-mode-map "\C-c\C-u" 'message-insert-or-toggle-importance)
2352   (define-key message-mode-map "\C-c\M-n"
2353     'message-insert-disposition-notification-to)
2354
2355   (define-key message-mode-map "\C-c\C-y" 'message-yank-original)
2356   (define-key message-mode-map "\C-c\M-\C-y" 'message-yank-buffer)
2357   (define-key message-mode-map "\C-c\C-q" 'message-fill-yanked-message)
2358   (define-key message-mode-map "\C-c\C-w" 'message-insert-signature)
2359   (define-key message-mode-map "\C-c\M-h" 'message-insert-headers)
2360   (define-key message-mode-map "\C-c\C-r" 'message-caesar-buffer-body)
2361   (define-key message-mode-map "\C-c\C-o" 'message-sort-headers)
2362   (define-key message-mode-map "\C-c\M-r" 'message-rename-buffer)
2363
2364   (define-key message-mode-map "\C-c\C-c" 'message-send-and-exit)
2365   (define-key message-mode-map "\C-c\C-s" 'message-send)
2366   (define-key message-mode-map "\C-c\C-k" 'message-kill-buffer)
2367   (define-key message-mode-map "\C-c\C-d" 'message-dont-send)
2368   (define-key message-mode-map "\C-c\n" 'gnus-delay-article)
2369
2370   (define-key message-mode-map "\C-c\C-e" 'message-elide-region)
2371   (define-key message-mode-map "\C-c\C-v" 'message-delete-not-region)
2372   (define-key message-mode-map "\C-c\C-z" 'message-kill-to-signature)
2373   (define-key message-mode-map "\M-\r" 'message-newline-and-reformat)
2374   ;;(define-key message-mode-map "\M-q" 'message-fill-paragraph)
2375   (define-key message-mode-map [remap split-line]  'message-split-line)
2376
2377   (define-key message-mode-map "\C-a" 'message-beginning-of-line)
2378   (define-key message-mode-map "\t" 'message-tab)
2379   (define-key message-mode-map "\M-;" 'comment-region)
2380
2381   (define-key message-mode-map "\C-xk" 'message-mimic-kill-buffer))
2382
2383 (easy-menu-define
2384  message-mode-menu message-mode-map "Message Menu."
2385  `("Message"
2386    ["Yank Original" message-yank-original t]
2387    ["Fill Yanked Message" message-fill-yanked-message t]
2388    ["Insert Signature" message-insert-signature t]
2389    ["Caesar (rot13) Message" message-caesar-buffer-body t]
2390    ["Caesar (rot13) Region" message-caesar-region (message-mark-active-p)]
2391    ["Elide Region" message-elide-region
2392     :active (message-mark-active-p)
2393     ,@(if (featurep 'xemacs) nil
2394         '(:help "Replace text in region with an ellipsis"))]
2395    ["Delete Outside Region" message-delete-not-region
2396     :active (message-mark-active-p)
2397     ,@(if (featurep 'xemacs) nil
2398         '(:help "Delete all quoted text outside region"))]
2399    ["Kill To Signature" message-kill-to-signature t]
2400    ["Newline and Reformat" message-newline-and-reformat t]
2401    ["Rename buffer" message-rename-buffer t]
2402    ["Spellcheck" ispell-message
2403     ,@(if (featurep 'xemacs) '(t)
2404         '(:help "Spellcheck this message"))]
2405    ["Attach file as MIME" mime-edit-insert-file
2406     ,@(if (featurep 'xemacs) '(t)
2407         '(:help "Attach a file at point"))]
2408    "----"
2409    ["Insert Region Marked" message-mark-inserted-region
2410     :active (message-mark-active-p)
2411     ,@(if (featurep 'xemacs) nil
2412         '(:help "Mark region with enclosing tags"))]
2413    ["Insert File Marked..." message-mark-insert-file
2414     ,@(if (featurep 'xemacs) '(t)
2415         '(:help "Insert file at point marked with enclosing tags"))]
2416    "----"
2417    ["Send Message" message-send-and-exit
2418     ,@(if (featurep 'xemacs) '(t)
2419         '(:help "Send this message"))]
2420    ["Postpone Message" message-dont-send
2421     ,@(if (featurep 'xemacs) '(t)
2422         '(:help "File this draft message and exit"))]
2423    ["Send at Specific Time..." gnus-delay-article
2424     ,@(if (featurep 'xemacs) '(t)
2425         '(:help "Ask, then arrange to send message at that time"))]
2426    ["Kill Message" message-kill-buffer
2427     ,@(if (featurep 'xemacs) '(t)
2428         '(:help "Delete this message without sending"))]))
2429
2430 (easy-menu-define
2431  message-mode-field-menu message-mode-map ""
2432  `("Field"
2433    ["To" message-goto-to t]
2434    ["From" message-goto-from t]
2435    ["Subject" message-goto-subject t]
2436    ["Change subject..." message-change-subject t]
2437    ["Cc" message-goto-cc t]
2438    ["Bcc" message-goto-bcc t]
2439    ["Fcc" message-goto-fcc t]
2440    ["Reply-To" message-goto-reply-to t]
2441    ["Flag As Important" message-insert-importance-high
2442     ,@(if (featurep 'xemacs) '(t)
2443         '(:help "Mark this message as important"))]
2444    ["Flag As Unimportant" message-insert-importance-low
2445     ,@(if (featurep 'xemacs) '(t)
2446         '(:help "Mark this message as unimportant"))]
2447    ["Request Receipt"
2448     message-insert-disposition-notification-to
2449     ,@(if (featurep 'xemacs) '(t)
2450         '(:help "Request a receipt notification"))]
2451    "----"
2452    ;; (typical) news stuff
2453    ["Summary" message-goto-summary t]
2454    ["Keywords" message-goto-keywords t]
2455    ["Newsgroups" message-goto-newsgroups t]
2456    ["Fetch Newsgroups" message-insert-newsgroups t]
2457    ["Followup-To" message-goto-followup-to t]
2458    ;; ["Followup-To (with note in body)" message-cross-post-followup-to t]
2459    ["Crosspost / Followup-To..." message-cross-post-followup-to t]
2460    ["Distribution" message-goto-distribution t]
2461    ["X-No-Archive:" message-add-archive-header t ]
2462    "----"
2463    ;; (typical) mailing-lists stuff
2464    ["Fetch To" message-insert-to
2465     ,@(if (featurep 'xemacs) '(t)
2466         '(:help "Insert a To header that points to the author."))]
2467    ["Fetch To and Cc" message-insert-wide-reply
2468     ,@(if (featurep 'xemacs) '(t)
2469         '(:help
2470           "Insert To and Cc headers as if you were doing a wide reply."))]
2471    "----"
2472    ["Send to list only" message-to-list-only t]
2473    ["Mail-Followup-To" message-goto-mail-followup-to t]
2474    ["Mail-Reply-To" message-goto-mail-reply-to t]
2475    ["Mail-Copies-To" message-goto-mail-copies-to t]
2476    ["Unsubscribed list post" message-generate-unsubscribed-mail-followup-to
2477     ,@(if (featurep 'xemacs) '(t)
2478         '(:help "Insert a reasonable `Mail-Followup-To:' header."))]
2479    ["Reduce To: to Cc:" message-reduce-to-to-cc t]
2480    "----"
2481    ["Sort Headers" message-sort-headers t]
2482    ["Encode non-ASCII domain names" message-idna-to-ascii-rhs t]
2483    ["Goto Body" message-goto-body t]
2484    ["Goto Signature" message-goto-signature t]))
2485
2486 (defvar message-tool-bar-map nil)
2487
2488 (eval-when-compile
2489   (defvar facemenu-add-face-function)
2490   (defvar facemenu-remove-face-function))
2491
2492 ;;; Forbidden properties
2493 ;;
2494 ;; We use `after-change-functions' to keep special text properties
2495 ;; that interfer with the normal function of message mode out of the
2496 ;; buffer.
2497
2498 (defcustom message-strip-special-text-properties t
2499   "Strip special properties from the message buffer.
2500
2501 Emacs has a number of special text properties which can break message
2502 composing in various ways.  If this option is set, message will strip
2503 these properties from the message composition buffer.  However, some
2504 packages requires these properties to be present in order to work.
2505 If you use one of these packages, turn this option off, and hope the
2506 message composition doesn't break too bad."
2507   :group 'message-various
2508   :type 'boolean)
2509
2510 (defconst message-forbidden-properties
2511   ;; No reason this should be clutter up customize.  We make it a
2512   ;; property list (rather than a list of property symbols), to be
2513   ;; directly useful for `remove-text-properties'.
2514   '(field nil read-only nil invisible nil intangible nil
2515           mouse-face nil modification-hooks nil insert-in-front-hooks nil
2516           insert-behind-hooks nil point-entered nil point-left nil)
2517   ;; Other special properties:
2518   ;; category, face, display: probably doesn't do any harm.
2519   ;; fontified: is used by font-lock.
2520   ;; syntax-table, local-map: I dunno.
2521   ;; We need to add XEmacs names to the list.
2522   "Property list of with properties.forbidden in message buffers.
2523 The values of the properties are ignored, only the property names are used.")
2524
2525 (defun message-tamago-not-in-use-p (pos)
2526   "Return t when tamago version 4 is not in use at the cursor position.
2527 Tamago version 4 is a popular input method for writing Japanese text.
2528 It uses the properties `intangible', `invisible', `modification-hooks'
2529 and `read-only' when translating ascii or kana text to kanji text.
2530 These properties are essential to work, so we should never strip them."
2531   (not (and (boundp 'egg-modefull-mode)
2532             (symbol-value 'egg-modefull-mode)
2533             (or (memq (get-text-property pos 'intangible)
2534                       '(its-part-1 its-part-2))
2535                 (get-text-property pos 'egg-end)
2536                 (get-text-property pos 'egg-lang)
2537                 (get-text-property pos 'egg-start)))))
2538
2539 (defun message-strip-forbidden-properties (begin end &optional old-length)
2540   "Strip forbidden properties between BEGIN and END, ignoring the third arg.
2541 This function is intended to be called from `after-change-functions'.
2542 See also `message-forbidden-properties'."
2543   (when (and message-strip-special-text-properties
2544              (message-tamago-not-in-use-p begin)
2545              ;; Check whether the invisible MIME part is not inserted.
2546              (not (text-property-any begin end 'mime-edit-invisible t)))
2547     (while (not (= begin end))
2548       (when (not (get-text-property begin 'message-hidden))
2549         (remove-text-properties begin (1+ begin)
2550                                 message-forbidden-properties))
2551       (incf begin))))
2552
2553 ;;;###autoload
2554 (define-derived-mode message-mode text-mode "Message"
2555   "Major mode for editing mail and news to be sent.
2556 Like Text Mode but with these additional commands:\\<message-mode-map>
2557 C-c C-s  `message-send' (send the message)  C-c C-c  `message-send-and-exit'
2558 C-c C-d  Postpone sending the message       C-c C-k  Kill the message
2559 C-c C-f  move to a header field (and create it if there isn't):
2560          C-c C-f C-t  move to To        C-c C-f C-s  move to Subject
2561          C-c C-f C-c  move to Cc        C-c C-f C-b  move to Bcc
2562          C-c C-f C-w  move to Fcc       C-c C-f C-r  move to Reply-To
2563          C-c C-f C-u  move to Summary   C-c C-f C-n  move to Newsgroups
2564          C-c C-f C-k  move to Keywords  C-c C-f C-d  move to Distribution
2565          C-c C-f C-o  move to From (\"Originator\")
2566          C-c C-f C-f  move to Followup-To
2567          C-c C-f C-m  move to Mail-Followup-To
2568          C-c C-f c    move to Mail-Copies-To
2569          C-c C-f C-i  cycle through Importance values
2570          C-c C-f s    change subject and append \"(was: <Old Subject>)\"
2571          C-c C-f x    crossposting with FollowUp-To header and note in body
2572          C-c C-f t    replace To: header with contents of Cc: or Bcc:
2573          C-c C-f a    Insert X-No-Archive: header and a note in the body
2574 C-c C-t  `message-insert-to' (add a To header to a news followup)
2575 C-c C-l  `message-to-list-only' (removes all but list address in to/cc)
2576 C-c C-n  `message-insert-newsgroups' (add a Newsgroup header to a news reply)
2577 C-c C-b  `message-goto-body' (move to beginning of message text).
2578 C-c C-i  `message-goto-signature' (move to the beginning of the signature).
2579 C-c C-w  `message-insert-signature' (insert `message-signature-file' file).
2580 C-c C-y  `message-yank-original' (insert current message, if any).
2581 C-c C-q  `message-fill-yanked-message' (fill what was yanked).
2582 C-c C-e  `message-elide-region' (elide the text between point and mark).
2583 C-c C-v  `message-delete-not-region' (remove the text outside the region).
2584 C-c C-z  `message-kill-to-signature' (kill the text up to the signature).
2585 C-c C-r  `message-caesar-buffer-body' (rot13 the message body).
2586 C-c C-u  `message-insert-or-toggle-importance'  (insert or cycle importance).
2587 C-c M-n  `message-insert-disposition-notification-to'  (request receipt).
2588 C-c M-m  `message-mark-inserted-region' (mark region with enclosing tags).
2589 C-c M-f  `message-mark-insert-file' (insert file marked with enclosing tags).
2590 M-RET    `message-newline-and-reformat' (break the line and reformat)."
2591   (setq local-abbrev-table text-mode-abbrev-table)
2592   (set (make-local-variable 'message-reply-buffer) nil)
2593   (set (make-local-variable 'message-inserted-headers) nil)
2594   (set (make-local-variable 'message-send-actions) nil)
2595   (set (make-local-variable 'message-exit-actions) nil)
2596   (set (make-local-variable 'message-kill-actions) nil)
2597   (set (make-local-variable 'message-postpone-actions) nil)
2598   (set (make-local-variable 'message-draft-article) nil)
2599   (setq buffer-offer-save t)
2600   (set (make-local-variable 'facemenu-add-face-function)
2601        (lambda (face end)
2602          (let ((face-fun (cdr (assq face message-face-alist))))
2603            (if face-fun
2604                (funcall face-fun (point) end)
2605              (error "Face %s not configured for %s mode" face mode-name)))
2606          ""))
2607   (set (make-local-variable 'facemenu-remove-face-function) t)
2608   (set (make-local-variable 'message-reply-headers) nil)
2609   (make-local-variable 'message-user-agent)
2610   (make-local-variable 'message-post-method)
2611   (set (make-local-variable 'message-sent-message-via) nil)
2612   (set (make-local-variable 'message-checksum) nil)
2613   (make-local-variable 'message-parameter-alist)
2614   (setq message-parameter-alist
2615         (copy-sequence message-startup-parameter-alist))
2616   (message-setup-fill-variables)
2617   (set
2618    (make-local-variable 'paragraph-separate)
2619    (format "\\(%s\\)\\|\\(%s\\)"
2620            paragraph-separate
2621            "<#!*/?\\(multipart\\|part\\|external\\|mml\\|secure\\)"))
2622   ;; Allow using comment commands to add/remove quoting.
2623   (set (make-local-variable 'comment-start) message-yank-prefix)
2624   (if (featurep 'xemacs)
2625       (message-setup-toolbar)
2626     (set (make-local-variable 'font-lock-defaults)
2627          '(message-font-lock-keywords t))
2628     (if (boundp 'tool-bar-map)
2629         (set (make-local-variable 'tool-bar-map) (message-tool-bar-map))))
2630   (easy-menu-add message-mode-menu message-mode-map)
2631   (easy-menu-add message-mode-field-menu message-mode-map)
2632   (gnus-make-local-hook 'after-change-functions)
2633   ;; Mmmm... Forbidden properties...
2634   (add-hook 'after-change-functions 'message-strip-forbidden-properties
2635             nil 'local)
2636   ;; Allow mail alias things.
2637   (when (eq message-mail-alias-type 'abbrev)
2638     (if (fboundp 'mail-abbrevs-setup)
2639         (mail-abbrevs-setup)
2640       (if (fboundp 'mail-aliases-setup) ; warning avoidance
2641           (mail-aliases-setup))))
2642   (unless buffer-file-name
2643     (message-set-auto-save-file-name))
2644   (set (make-local-variable 'indent-tabs-mode) nil)) ;No tabs for indentation.
2645
2646 (defun message-setup-fill-variables ()
2647   "Setup message fill variables."
2648   (set (make-local-variable 'fill-paragraph-function)
2649        'message-fill-paragraph)
2650   (make-local-variable 'paragraph-separate)
2651   (make-local-variable 'paragraph-start)
2652   (make-local-variable 'adaptive-fill-regexp)
2653   (unless (boundp 'adaptive-fill-first-line-regexp)
2654     (setq adaptive-fill-first-line-regexp nil))
2655   (make-local-variable 'adaptive-fill-first-line-regexp)
2656   (let ((quote-prefix-regexp
2657          ;; User should change message-cite-prefix-regexp if
2658          ;; message-yank-prefix is set to an abnormal value.
2659          (concat "\\(" message-cite-prefix-regexp "\\)[ \t]*")))
2660     (setq paragraph-start
2661           (concat
2662            (regexp-quote mail-header-separator) "$\\|"
2663            "[ \t]*$\\|"                 ; blank lines
2664            "-- $\\|"                    ; signature delimiter
2665            "---+$\\|"                   ; delimiters for forwarded messages
2666            page-delimiter "$\\|"        ; spoiler warnings
2667            ".*wrote:$\\|"               ; attribution lines
2668            quote-prefix-regexp "$"))    ; empty lines in quoted text
2669     (setq paragraph-separate paragraph-start)
2670     (setq adaptive-fill-regexp
2671           (concat quote-prefix-regexp "\\|" adaptive-fill-regexp))
2672     (setq adaptive-fill-first-line-regexp
2673           (concat quote-prefix-regexp "\\|"
2674                   adaptive-fill-first-line-regexp)))
2675   (make-local-variable 'auto-fill-inhibit-regexp)
2676   ;;(setq auto-fill-inhibit-regexp "^[A-Z][^: \n\t]+:")
2677   (setq auto-fill-inhibit-regexp nil)
2678   (make-local-variable 'normal-auto-fill-function)
2679   (setq normal-auto-fill-function 'message-do-auto-fill)
2680   ;; KLUDGE: auto fill might already be turned on in `text-mode-hook'.
2681   ;; In that case, ensure that it uses the right function.  The real
2682   ;; solution would be not to use `define-derived-mode', and run
2683   ;; `text-mode-hook' ourself at the end of the mode.
2684   ;; -- Per Abrahamsen <abraham@dina.kvl.dk> Date: 2001-10-19.
2685   (when auto-fill-function
2686     (setq auto-fill-function normal-auto-fill-function)))
2687
2688 \f
2689
2690 ;;;
2691 ;;; Message mode commands
2692 ;;;
2693
2694 ;;; Movement commands
2695
2696 (defun message-goto-to ()
2697   "Move point to the To header."
2698   (interactive)
2699   (message-position-on-field "To"))
2700
2701 (defun message-goto-from ()
2702   "Move point to the From header."
2703   (interactive)
2704   (message-position-on-field "From"))
2705
2706 (defun message-goto-subject ()
2707   "Move point to the Subject header."
2708   (interactive)
2709   (message-position-on-field "Subject"))
2710
2711 (defun message-goto-cc ()
2712   "Move point to the Cc header."
2713   (interactive)
2714   (message-position-on-field "Cc" "To"))
2715
2716 (defun message-goto-bcc ()
2717   "Move point to the Bcc  header."
2718   (interactive)
2719   (message-position-on-field "Bcc" "Cc" "To"))
2720
2721 (defun message-goto-fcc ()
2722   "Move point to the Fcc header."
2723   (interactive)
2724   (message-position-on-field "Fcc" "To" "Newsgroups"))
2725
2726 (defun message-goto-reply-to ()
2727   "Move point to the Reply-To header."
2728   (interactive)
2729   (message-position-on-field "Reply-To" "Subject"))
2730
2731 (defun message-goto-mail-reply-to ()
2732   "Move point to the Mail-Reply-To header."
2733   (interactive)
2734   (message-position-on-field "Mail-Reply-To" "Subject"))
2735
2736 (defun message-goto-mail-copies-to ()
2737   "Move point to the Mail-Copies-To header.  If the header is newly created,
2738 a string \"never\" is inserted in default."
2739   (interactive)
2740   (unless (message-position-on-field "Mail-Copies-To" "Subject")
2741     (insert "never")
2742     (backward-char 5)))
2743
2744 (defun message-goto-newsgroups ()
2745   "Move point to the Newsgroups header."
2746   (interactive)
2747   (message-position-on-field "Newsgroups"))
2748
2749 (defun message-goto-distribution ()
2750   "Move point to the Distribution header."
2751   (interactive)
2752   (message-position-on-field "Distribution"))
2753
2754 (defun message-goto-followup-to ()
2755   "Move point to the Followup-To header."
2756   (interactive)
2757   (message-position-on-field "Followup-To" "Newsgroups"))
2758
2759 (defun message-goto-mail-followup-to ()
2760   "Move point to the Mail-Followup-To header.  If the header is newly created
2761 and To field contains only one address, the address is inserted in default."
2762   (interactive)
2763   (unless (message-position-on-field "Mail-Followup-To" "Subject")
2764     (let ((start (point))
2765           addresses)
2766       (save-restriction
2767         (message-narrow-to-headers)
2768         (setq addresses (split-string (mail-strip-quoted-names
2769                                        (or (std11-fetch-field "to") ""))
2770                                       "[ \f\t\n\r\v,]+"))
2771         (when (eq 1 (length addresses))
2772           (goto-char start)
2773           (insert (car addresses))
2774           (goto-char start))))))
2775
2776 (defun message-goto-keywords ()
2777   "Move point to the Keywords header."
2778   (interactive)
2779   (message-position-on-field "Keywords" "Subject"))
2780
2781 (defun message-goto-summary ()
2782   "Move point to the Summary header."
2783   (interactive)
2784   (message-position-on-field "Summary" "Subject"))
2785
2786 (defun message-goto-body (&optional interactivep)
2787   "Move point to the beginning of the message body."
2788   (interactive (list t))
2789   (when (and interactivep
2790              (looking-at "[ \t]*\n"))
2791     (expand-abbrev))
2792   (goto-char (point-min))
2793   (or (search-forward (concat "\n" mail-header-separator "\n") nil t)
2794       (search-forward-regexp "[^:]+:\\([^\n]\\|\n[ \t]\\)+\n\n" nil t)))
2795
2796 (defun message-goto-eoh ()
2797   "Move point to the end of the headers."
2798   (interactive)
2799   (message-goto-body)
2800   (forward-line -1))
2801
2802 (defun message-goto-signature ()
2803   "Move point to the beginning of the message signature.
2804 If there is no signature in the article, go to the end and
2805 return nil."
2806   (interactive)
2807   (goto-char (point-min))
2808   (if (re-search-forward message-signature-separator nil t)
2809       (forward-line 1)
2810     (goto-char (point-max))
2811     nil))
2812
2813 (defun message-generate-unsubscribed-mail-followup-to (&optional include-cc)
2814   "Insert a reasonable MFT header in a post to an unsubscribed list.
2815 When making original posts to a mailing list you are not subscribed to,
2816 you have to type in a MFT header by hand.  The contents, usually, are
2817 the addresses of the list and your own address.  This function inserts
2818 such a header automatically.  It fetches the contents of the To: header
2819 in the current mail buffer, and appends the current `user-mail-address'.
2820
2821 If the optional argument INCLUDE-CC is non-nil, the addresses in the
2822 Cc: header are also put into the MFT."
2823
2824   (interactive "P")
2825   (let* (cc tos)
2826     (save-restriction
2827       (message-narrow-to-headers)
2828       (message-remove-header "Mail-Followup-To")
2829       (setq cc (and include-cc (message-fetch-field "Cc")))
2830       (setq tos (if cc
2831                     (concat (message-fetch-field "To") "," cc)
2832                   (message-fetch-field "To"))))
2833     (message-goto-mail-followup-to)
2834     (insert (concat tos ", " user-mail-address))))
2835
2836 \f
2837
2838 (defun message-insert-to (&optional force)
2839   "Insert a To header that points to the author of the article being replied to.
2840 If the original author requested not to be sent mail, don't insert unless the
2841 prefix FORCE is given."
2842   (interactive "P")
2843   (let* ((mct (message-fetch-reply-field "mail-copies-to"))
2844          (dont (and mct (or (equal (downcase mct) "never")
2845                             (equal (downcase mct) "nobody"))))
2846          (to (or (message-fetch-reply-field "mail-reply-to")
2847                  (message-fetch-reply-field "reply-to")
2848                  (message-fetch-reply-field "from"))))
2849     (when (and dont to)
2850       (gnus-message
2851        3
2852        (if force
2853            "Ignoring the user request not to have copies sent via mail"
2854          "Complying with the user request not to have copies sent via mail")))
2855     (when (and force (not to))
2856       (error "No mail address in the article"))
2857     (when (and to (or force (not dont)))
2858       (message-carefully-insert-headers (list (cons 'To to))))))
2859
2860 (defun message-insert-wide-reply ()
2861   "Insert To and Cc headers as if you were doing a wide reply."
2862   (interactive)
2863   (let ((headers (message-with-reply-buffer
2864                    (message-get-reply-headers t))))
2865     (message-carefully-insert-headers headers)))
2866
2867 (defun message-carefully-insert-headers (headers)
2868   (dolist (header headers)
2869     (let ((header-name (symbol-name (car header))))
2870       (when (and (message-position-on-field header-name)
2871                  (mail-fetch-field header-name)
2872                  (not (string-match "\\` *\\'"
2873                                     (mail-fetch-field header-name))))
2874         (insert ", "))
2875       (insert (cdr header)))))
2876
2877 (defun message-widen-reply ()
2878   "Widen the reply to include maximum recipients."
2879   (interactive)
2880   (let ((follow-to
2881          (and message-reply-buffer
2882               (buffer-name message-reply-buffer)
2883               (save-excursion
2884                 (set-buffer message-reply-buffer)
2885                 (message-get-reply-headers t)))))
2886     (save-excursion
2887       (save-restriction
2888         (message-narrow-to-headers)
2889         (dolist (elem follow-to)
2890           (message-remove-header (symbol-name (car elem)))
2891           (goto-char (point-min))
2892           (insert (symbol-name (car elem)) ": "
2893                   (cdr elem) "\n"))))))
2894
2895 (defun message-insert-newsgroups ()
2896   "Insert the Newsgroups header from the article being replied to."
2897   (interactive)
2898   (when (and (message-position-on-field "Newsgroups")
2899              (mail-fetch-field "newsgroups")
2900              (not (string-match "\\` *\\'" (mail-fetch-field "newsgroups"))))
2901     (insert ","))
2902   (insert (or (message-fetch-reply-field "newsgroups") "")))
2903
2904 \f
2905
2906 ;;; Various commands
2907
2908 (defun message-delete-not-region (beg end)
2909   "Delete everything in the body of the current message outside of the region."
2910   (interactive "r")
2911   (let (citeprefix)
2912     (save-excursion
2913       (goto-char beg)
2914       ;; snarf citation prefix, if appropriate
2915       (unless (eq (point) (progn (beginning-of-line) (point)))
2916         (when (looking-at message-cite-prefix-regexp)
2917           (setq citeprefix (match-string 0))))
2918       (goto-char end)
2919       (delete-region (point) (if (not (message-goto-signature))
2920                                  (point)
2921                                (forward-line -2)
2922                                (point)))
2923       (insert "\n")
2924       (goto-char beg)
2925       (delete-region beg (progn (message-goto-body)
2926                                 (forward-line 2)
2927                                 (point)))
2928       (when citeprefix
2929         (insert citeprefix))))
2930   (when (message-goto-signature)
2931     (forward-line -2)))
2932
2933 (defun message-kill-to-signature ()
2934   "Deletes all text up to the signature."
2935   (interactive)
2936   (let ((point (point)))
2937     (message-goto-signature)
2938     (unless (eobp)
2939       (end-of-line -1))
2940     (kill-region point (point))
2941     (unless (bolp)
2942       (insert "\n"))))
2943
2944 (defun message-newline-and-reformat (&optional arg not-break)
2945   "Insert four newlines, and then reformat if inside quoted text.
2946 Prefix arg means justify as well."
2947   (interactive (list (if current-prefix-arg 'full)))
2948   (let (quoted point beg end leading-space bolp)
2949     (setq point (point))
2950     (beginning-of-line)
2951     (setq beg (point))
2952     (setq bolp (= beg point))
2953     ;; Find first line of the paragraph.
2954     (if not-break
2955         (while (and (not (eobp))
2956                     (not (looking-at message-cite-prefix-regexp))
2957                     (looking-at paragraph-start))
2958           (forward-line 1)))
2959     ;; Find the prefix
2960     (when (looking-at message-cite-prefix-regexp)
2961       (setq quoted (match-string 0))
2962       (goto-char (match-end 0))
2963       (looking-at "[ \t]*")
2964       (setq leading-space (match-string 0)))
2965     (if (and quoted
2966              (not not-break)
2967              (not bolp)
2968              (< (- point beg) (length quoted)))
2969         ;; break inside the cite prefix.
2970         (setq quoted nil
2971               end nil))
2972     (if quoted
2973         (progn
2974           (forward-line 1)
2975           (while (and (not (eobp))
2976                       (not (looking-at paragraph-separate))
2977                       (looking-at message-cite-prefix-regexp)
2978                       (equal quoted (match-string 0)))
2979             (goto-char (match-end 0))
2980             (looking-at "[ \t]*")
2981             (if (> (length leading-space) (length (match-string 0)))
2982                 (setq leading-space (match-string 0)))
2983             (forward-line 1))
2984           (setq end (point))
2985           (goto-char beg)
2986           (while (and (if (bobp) nil (forward-line -1) t)
2987                       (not (looking-at paragraph-start))
2988                       (looking-at message-cite-prefix-regexp)
2989                       (equal quoted (match-string 0)))
2990             (setq beg (point))
2991             (goto-char (match-end 0))
2992             (looking-at "[ \t]*")
2993             (if (> (length leading-space) (length (match-string 0)))
2994                 (setq leading-space (match-string 0)))))
2995       (while (and (not (eobp))
2996                   (not (looking-at paragraph-separate))
2997                   (not (looking-at message-cite-prefix-regexp)))
2998         (forward-line 1))
2999       (setq end (point))
3000       (goto-char beg)
3001       (while (and (if (bobp) nil (forward-line -1) t)
3002                   (not (looking-at paragraph-start))
3003                   (not (looking-at message-cite-prefix-regexp)))
3004         (setq beg (point))))
3005     (goto-char point)
3006     (save-restriction
3007       (narrow-to-region beg end)
3008       (if not-break
3009           (setq point nil)
3010         (if bolp
3011             (newline)
3012           (newline)
3013           (newline))
3014         (setq point (point))
3015         ;; (newline 2) doesn't mark both newline's as hard, so call
3016         ;; newline twice. -jas
3017         (newline)
3018         (newline)
3019         (delete-region (point) (re-search-forward "[ \t]*"))
3020         (when (and quoted (not bolp))
3021           (insert quoted leading-space)))
3022       (undo-boundary)
3023       (if quoted
3024           (let* ((adaptive-fill-regexp
3025                   (regexp-quote (concat quoted leading-space)))
3026                  (adaptive-fill-first-line-regexp
3027                   adaptive-fill-regexp ))
3028             (fill-paragraph arg))
3029         (fill-paragraph arg))
3030       (if point (goto-char point)))))
3031
3032 (defun message-fill-paragraph (&optional arg)
3033   "Like `fill-paragraph'."
3034   (interactive (list (if current-prefix-arg 'full)))
3035   (if (if (boundp 'filladapt-mode) filladapt-mode)
3036       nil
3037     (message-newline-and-reformat arg t)
3038     t))
3039
3040 ;; Is it better to use `mail-header-end'?
3041 (defun message-point-in-header-p ()
3042   "Return t if point is in the header."
3043   (save-excursion
3044     (let ((p (point)))
3045       (goto-char (point-min))
3046       (not (re-search-forward
3047             (concat "^" (regexp-quote mail-header-separator) "\n")
3048             p t)))))
3049
3050 (defun message-do-auto-fill ()
3051   "Like `do-auto-fill', but don't fill in message header."
3052   (unless (message-point-in-header-p)
3053     (do-auto-fill)))
3054
3055 (defun message-insert-signature (&optional force)
3056   "Insert a signature.  See documentation for variable `message-signature'."
3057   (interactive (list 0))
3058   (let* ((signature
3059           (cond
3060            ((and (null message-signature)
3061                  (eq force 0))
3062             (save-excursion
3063               (goto-char (point-max))
3064               (not (re-search-backward message-signature-separator nil t))))
3065            ((and (null message-signature)
3066                  force)
3067             t)
3068            ((functionp message-signature)
3069             (funcall message-signature))
3070            ((listp message-signature)
3071             (eval message-signature))
3072            (t message-signature)))
3073          (signature
3074           (cond ((stringp signature)
3075                  signature)
3076                 ((and (eq t signature)
3077                       message-signature-file
3078                       (file-exists-p message-signature-file))
3079                  signature))))
3080     (when signature
3081       (goto-char (point-max))
3082       ;; Insert the signature.
3083       (unless (bolp)
3084         (insert "\n"))
3085       (when message-signature-insert-empty-line
3086         (insert "\n"))
3087       (insert "\n" message-signature-separator-for-insertion)
3088       (unless (bolp)
3089         (insert "\n"))
3090       (if (eq signature t)
3091           (insert-file-contents message-signature-file)
3092         (insert signature))
3093       (goto-char (point-max))
3094       (or (bolp) (insert "\n")))))
3095
3096 (defun message-insert-importance-high ()
3097   "Insert header to mark message as important."
3098   (interactive)
3099   (save-excursion
3100     (save-restriction
3101       (message-narrow-to-headers)
3102       (message-remove-header "Importance"))
3103     (message-goto-eoh)
3104     (insert "Importance: high\n")))
3105
3106 (defun message-insert-importance-low ()
3107   "Insert header to mark message as unimportant."
3108   (interactive)
3109   (save-excursion
3110     (save-restriction
3111       (message-narrow-to-headers)
3112       (message-remove-header "Importance"))
3113     (message-goto-eoh)
3114     (insert "Importance: low\n")))
3115
3116 (defun message-insert-or-toggle-importance ()
3117   "Insert a \"Importance: high\" header, or cycle through the header values.
3118 The three allowed values according to RFC 1327 are `high', `normal'
3119 and `low'."
3120   (interactive)
3121   (save-excursion
3122     (let ((valid '("high" "normal" "low"))
3123           (new "high")
3124           cur)
3125       (save-restriction
3126         (message-narrow-to-headers)
3127         (when (setq cur (message-fetch-field "Importance"))
3128           (message-remove-header "Importance")
3129           (setq new (cond ((string= cur "high")
3130                            "low")
3131                           ((string= cur "low")
3132                            "normal")
3133                           (t
3134                            "high")))))
3135       (message-goto-eoh)
3136       (insert (format "Importance: %s\n" new)))))
3137
3138 (defun message-insert-disposition-notification-to ()
3139   "Request a disposition notification (return receipt) to this message.
3140 Note that this should not be used in newsgroups."
3141   (interactive)
3142   (save-excursion
3143     (save-restriction
3144       (message-narrow-to-headers)
3145       (message-remove-header "Disposition-Notification-To"))
3146     (message-goto-eoh)
3147     (insert (format "Disposition-Notification-To: %s\n"
3148                     (or (message-field-value "Reply-to")
3149                         (message-field-value "From")
3150                         (message-make-from))))))
3151
3152 (defun message-elide-region (b e)
3153   "Elide the text in the region.
3154 An ellipsis (from `message-elide-ellipsis') will be inserted where the
3155 text was killed."
3156   (interactive "r")
3157   (kill-region b e)
3158   (insert message-elide-ellipsis))
3159
3160 (defvar message-caesar-translation-table nil)
3161
3162 (defun message-caesar-region (b e &optional n)
3163   "Caesar rotate region B to E by N, default 13, for decrypting netnews."
3164   (interactive
3165    (list
3166     (min (point) (or (mark t) (point)))
3167     (max (point) (or (mark t) (point)))
3168     (when current-prefix-arg
3169       (prefix-numeric-value current-prefix-arg))))
3170
3171   (setq n (if (numberp n) (mod n 26) 13)) ;canonize N
3172   (unless (or (zerop n)                 ; no action needed for a rot of 0
3173               (= b e))                  ; no region to rotate
3174     ;; We build the table, if necessary.
3175     (when (or (not message-caesar-translation-table)
3176               (/= (aref message-caesar-translation-table ?a) (+ ?a n)))
3177       (setq message-caesar-translation-table
3178             (message-make-caesar-translation-table n)))
3179     (translate-region b e message-caesar-translation-table)))
3180
3181 (defun message-make-caesar-translation-table (n)
3182   "Create a rot table with offset N."
3183   (let ((i -1)
3184         (table (make-string 256 0)))
3185     (while (< (incf i) 256)
3186       (aset table i i))
3187     (concat
3188      (substring table 0 ?A)
3189      (substring table (+ ?A n) (+ ?A n (- 26 n)))
3190      (substring table ?A (+ ?A n))
3191      (substring table (+ ?A 26) ?a)
3192      (substring table (+ ?a n) (+ ?a n (- 26 n)))
3193      (substring table ?a (+ ?a n))
3194      (substring table (+ ?a 26) 255))))
3195
3196 (defun message-caesar-buffer-body (&optional rotnum)
3197   "Caesar rotate all letters in the current buffer by 13 places.
3198 Used to encode/decode possibly offensive messages (commonly in rec.humor).
3199 With prefix arg, specifies the number of places to rotate each letter forward.
3200 Mail and USENET news headers are not rotated."
3201   (interactive (if current-prefix-arg
3202                    (list (prefix-numeric-value current-prefix-arg))
3203                  (list nil)))
3204   (save-excursion
3205     (save-restriction
3206       (when (message-goto-body)
3207         (narrow-to-region (point) (point-max)))
3208       (message-caesar-region (point-min) (point-max) rotnum))))
3209
3210 (defun message-pipe-buffer-body (program)
3211   "Pipe the message body in the current buffer through PROGRAM."
3212   (save-excursion
3213     (save-restriction
3214       (when (message-goto-body)
3215         (narrow-to-region (point) (point-max)))
3216       (shell-command-on-region
3217        (point-min) (point-max) program nil t))))
3218
3219 (defun message-rename-buffer (&optional enter-string)
3220   "Rename the *message* buffer to \"*message* RECIPIENT\".
3221 If the function is run with a prefix, it will ask for a new buffer
3222 name, rather than giving an automatic name."
3223   (interactive "Pbuffer name: ")
3224   (save-excursion
3225     (save-restriction
3226       (goto-char (point-min))
3227       (narrow-to-region (point)
3228                         (search-forward mail-header-separator nil 'end))
3229       (let* ((mail-to (or
3230                        (if (message-news-p) (message-fetch-field "Newsgroups")
3231                          (message-fetch-field "To"))
3232                        ""))
3233              (mail-trimmed-to
3234               (if (string-match "," mail-to)
3235                   (concat (substring mail-to 0 (match-beginning 0)) ", ...")
3236                 mail-to))
3237              (name-default (concat "*message* " mail-trimmed-to))
3238              (name (if enter-string
3239                        (read-string "New buffer name: " name-default)
3240                      name-default)))
3241         (rename-buffer name t)))))
3242
3243 (defun message-fill-yanked-message (&optional justifyp)
3244   "Fill the paragraphs of a message yanked into this one.
3245 Numeric argument means justify as well."
3246   (interactive "P")
3247   (save-excursion
3248     (goto-char (point-min))
3249     (search-forward (concat "\n" mail-header-separator "\n") nil t)
3250     (let ((fill-prefix message-yank-prefix))
3251       (fill-individual-paragraphs (point) (point-max) justifyp))))
3252
3253 (defun message-indent-citation ()
3254   "Modify text just inserted from a message to be cited.
3255 The inserted text should be the region.
3256 When this function returns, the region is again around the modified text.
3257
3258 Normally, indent each nonblank line `message-indentation-spaces' spaces.
3259 However, if `message-yank-prefix' is non-nil, insert that prefix on each line."
3260   (let ((start (point)))
3261     ;; Remove unwanted headers.
3262     (when message-ignored-cited-headers
3263       (let (all-removed)
3264         (save-restriction
3265           (narrow-to-region
3266            (goto-char start)
3267            (if (search-forward "\n\n" nil t)
3268                (1- (point))
3269              (point)))
3270           (message-remove-header message-ignored-cited-headers t)
3271           (when (= (point-min) (point-max))
3272             (setq all-removed t))
3273           (goto-char (point-max)))
3274         (if all-removed
3275             (goto-char start)
3276           (forward-line 1))))
3277     ;; Delete blank lines at the start of the buffer.
3278     (while (and (point-min)
3279                 (eolp)
3280                 (not (eobp)))
3281       (message-delete-line))
3282     ;; Delete blank lines at the end of the buffer.
3283     (goto-char (point-max))
3284     (unless (bolp)
3285       (insert "\n"))
3286     (while (and (zerop (forward-line -1))
3287                 (looking-at "$"))
3288       (message-delete-line))
3289     ;; Do the indentation.
3290     (if (null message-yank-prefix)
3291         (indent-rigidly start (mark t) message-indentation-spaces)
3292       (save-excursion
3293         (goto-char start)
3294         (while (< (point) (mark t))
3295           (if (or (looking-at ">") (looking-at "^$"))
3296               (insert message-yank-cited-prefix)
3297             (insert message-yank-prefix))
3298           (forward-line 1))))
3299     (goto-char start)))
3300
3301 (defun message-list-references (refs-list &rest refs-strs)
3302   "Add `Message-ID's which appear in REFS-STRS but not in REFS-LIST,
3303 to REFS-LIST."
3304   (let (refs ref id saved-id)
3305     (when (and refs-list
3306                (integerp message-list-references-add-position))
3307       (let ((pos message-list-references-add-position))
3308         (while (and refs-list
3309                     (> pos 0))
3310           (push (pop refs-list) saved-id)
3311           (setq pos (1- pos)))))
3312     (while refs-strs
3313       (when (setq refs (pop refs-strs))
3314         (setq refs (std11-parse-msg-ids (std11-lexical-analyze refs)))
3315         (while refs
3316           (when (eq (car (setq ref (pop refs))) 'msg-id)
3317             (setq id (concat "<" (mapconcat 'cdr (cdr ref) "") ">"))
3318             (or (member id refs-list)
3319                 (member id saved-id)
3320                 (push id refs-list))))))
3321     (while saved-id
3322       (push (pop saved-id) refs-list))
3323     refs-list))
3324
3325 (defun message-yank-original (&optional arg)
3326   "Insert the message being replied to, if any.
3327 Puts point before the text and mark after.
3328 Normally indents each nonblank line ARG spaces (default 3).  However,
3329 if `message-yank-prefix' is non-nil, insert that prefix on each line.
3330
3331 This function uses `message-cite-function' to do the actual citing.
3332
3333 Just \\[universal-argument] as argument means don't indent, insert no
3334 prefix, and don't delete any headers.
3335
3336 In addition, if `message-yank-add-new-references' is non-nil and this
3337 command is called interactively, new IDs from the yanked article will
3338 be added to the \"References\" field."
3339   (interactive "P")
3340   (let ((modified (buffer-modified-p)))
3341     (when (let ((buffer (message-eval-parameter message-reply-buffer)))
3342             (and buffer
3343                  message-cite-function
3344                  (prog1
3345                      t
3346                    (delete-windows-on buffer t)
3347                    ; The mark will be set at the end of the article.
3348                    (insert-buffer buffer))))
3349       ;; Add new IDs to the References field.
3350       (when (and message-yank-add-new-references
3351                  (interactive-p))
3352         (let ((start (point))
3353               (end (mark t))
3354               refs newrefs)
3355           (save-excursion
3356             (save-restriction
3357               (widen)
3358               (setq refs (message-list-references
3359                           nil
3360                           (or (message-make-references)
3361                               (prog2
3362                                   (message-narrow-to-headers)
3363                                   (message-fetch-field "References")
3364                                 (widen)))))
3365               (narrow-to-region start end)
3366               (std11-narrow-to-header)
3367               (unless (equal (setq newrefs
3368                                    (message-list-references
3369                                     (copy-sequence refs)
3370                                     (unless (eq message-yank-add-new-references
3371                                                 'message-id-only)
3372                                       (or (message-fetch-field "References")
3373                                           (message-fetch-field "In-Reply-To")))
3374                                     (message-fetch-field "Message-ID")))
3375                              refs)
3376                 ;; If the References field has been changed, we make it
3377                 ;; visible in the header.
3378                 (when message-reply-headers
3379                   (mail-header-set-message-id message-reply-headers nil)
3380                   (mail-header-set-references message-reply-headers nil))
3381                 (widen)
3382                 (message-narrow-to-headers)
3383                 (if (let ((case-fold-search t))
3384                       (re-search-forward "^References:\\([\t ]+.+\n\\)+"
3385                                          nil t))
3386                     (replace-match "")
3387                   (goto-char (point-max)))
3388                 (mail-header-format
3389                  (list (or (assq 'References message-header-format-alist)
3390                            '(References . message-fill-references)))
3391                  (list (cons 'References (mapconcat 'identity
3392                                                     (nreverse newrefs) " "))))
3393                 (backward-delete-char 1))))))
3394       (unless arg
3395         (if (and message-suspend-font-lock-when-citing
3396                  (boundp 'font-lock-mode)
3397                  (symbol-value 'font-lock-mode))
3398             (unwind-protect
3399                 (progn
3400                   (sit-for 0)
3401                   (font-lock-mode 0)
3402                   (funcall message-cite-function))
3403               (font-lock-mode 1))
3404           (funcall message-cite-function)))
3405       (message-exchange-point-and-mark)
3406       (unless (bolp)
3407         (insert ?\n))
3408       (unless modified
3409         (setq message-checksum (message-checksum))))))
3410
3411 (defun message-yank-buffer (buffer)
3412   "Insert BUFFER into the current buffer and quote it."
3413   (interactive "bYank buffer: ")
3414   (let ((message-reply-buffer buffer))
3415     (save-window-excursion
3416       (message-yank-original))))
3417
3418 (defun message-buffers ()
3419   "Return a list of active message buffers."
3420   (let (buffers)
3421     (save-excursion
3422       (dolist (buffer (buffer-list t))
3423         (set-buffer buffer)
3424         (when (and (eq major-mode 'message-mode)
3425                    (null message-sent-message-via))
3426           (push (buffer-name buffer) buffers))))
3427     (nreverse buffers)))
3428
3429 (defun message-cite-original-without-signature ()
3430   "Cite function in the standard Message manner."
3431   (let ((start (point))
3432         (end (mark t))
3433         (functions
3434          (when message-indent-citation-function
3435            (if (listp message-indent-citation-function)
3436                message-indent-citation-function
3437              (list message-indent-citation-function))))
3438         (message-reply-headers (or message-reply-headers
3439                                    (make-mail-header))))
3440     (mail-header-set-from message-reply-headers
3441                           (save-restriction
3442                             (narrow-to-region
3443                              (point)
3444                              (if (search-forward "\n\n" nil t)
3445                                  (1- (point))
3446                                (point-max)))
3447                             (or (message-fetch-field "from")
3448                                 "unknown sender")))
3449     ;; Allow undoing.
3450     (undo-boundary)
3451     (goto-char end)
3452     (when (re-search-backward message-signature-separator start t)
3453       ;; Also peel off any blank lines before the signature.
3454       (forward-line -1)
3455       (while (looking-at "^[ \t]*$")
3456         (forward-line -1))
3457       (forward-line 1)
3458       (delete-region (point) end)
3459       (unless (search-backward "\n\n" start t)
3460         ;; Insert a blank line if it is peeled off.
3461         (insert "\n")))
3462     (goto-char start)
3463     (while functions
3464       (funcall (pop functions)))
3465     (when message-citation-line-function
3466       (unless (bolp)
3467         (insert "\n"))
3468       (funcall message-citation-line-function))))
3469
3470 (eval-when-compile (defvar mail-citation-hook))         ;Compiler directive
3471 (defun message-cite-original ()
3472   "Cite function in the standard Message manner."
3473   (if (and (boundp 'mail-citation-hook)
3474            mail-citation-hook)
3475       (run-hooks 'mail-citation-hook)
3476     (let ((start (point))
3477           (end (mark t))
3478           (functions
3479            (when message-indent-citation-function
3480              (if (listp message-indent-citation-function)
3481                  message-indent-citation-function
3482                (list message-indent-citation-function))))
3483           (message-reply-headers (or message-reply-headers
3484                                      (make-mail-header))))
3485       (mail-header-set-from message-reply-headers
3486                             (save-restriction
3487                               (narrow-to-region
3488                                (point)
3489                                (if (search-forward "\n\n" nil t)
3490                                    (1- (point))
3491                                  (point-max)))
3492                               (or (message-fetch-field "from")
3493                                   "unknown sender")))
3494       (goto-char start)
3495       (while functions
3496         (funcall (pop functions)))
3497       (when message-citation-line-function
3498         (unless (bolp)
3499           (insert "\n"))
3500         (funcall message-citation-line-function)))))
3501
3502 (defun message-insert-citation-line ()
3503   "Insert a simple citation line."
3504   (when message-reply-headers
3505     (insert (mail-header-from message-reply-headers) " writes:\n\n")))
3506
3507 (defun message-position-on-field (header &rest afters)
3508   (let ((case-fold-search t))
3509     (save-restriction
3510       (narrow-to-region
3511        (goto-char (point-min))
3512        (progn
3513          (re-search-forward
3514           (concat "^" (regexp-quote mail-header-separator) "$"))
3515          (match-beginning 0)))
3516       (goto-char (point-min))
3517       (if (re-search-forward (concat "^" (regexp-quote header) ":") nil t)
3518           (progn
3519             (re-search-forward "^[^ \t]" nil 'move)
3520             (beginning-of-line)
3521             (skip-chars-backward "\n")
3522             t)
3523         (while (and afters
3524                     (not (re-search-forward
3525                           (concat "^" (regexp-quote (car afters)) ":")
3526                           nil t)))
3527           (pop afters))
3528         (when afters
3529           (re-search-forward "^[^ \t]" nil 'move)
3530           (beginning-of-line))
3531         (insert header ": \n")
3532         (forward-char -1)
3533         nil))))
3534
3535 (defun message-remove-signature ()
3536   "Remove the signature from the text between point and mark.
3537 The text will also be indented the normal way."
3538   (save-excursion
3539     (let ((start (point))
3540           mark)
3541       (if (not (re-search-forward message-signature-separator (mark t) t))
3542           ;; No signature here, so we just indent the cited text.
3543           (message-indent-citation)
3544         ;; Find the last non-empty line.
3545         (forward-line -1)
3546         (while (looking-at "[ \t]*$")
3547           (forward-line -1))
3548         (forward-line 1)
3549         (setq mark (set-marker (make-marker) (point)))
3550         (goto-char start)
3551         (message-indent-citation)
3552         ;; Enable undoing the deletion.
3553         (undo-boundary)
3554         (delete-region mark (mark t))
3555         (set-marker mark nil)))))
3556
3557 \f
3558
3559 ;;;
3560 ;;; Sending messages
3561 ;;;
3562
3563 ;; Avoid byte-compile warning.
3564 (defvar message-encoding-buffer nil)
3565 (defvar message-edit-buffer nil)
3566 (defvar message-mime-mode nil)
3567
3568 (defun message-send-and-exit (&optional arg)
3569   "Send message like `message-send', then, if no errors, exit from mail buffer."
3570   (interactive "P")
3571   (let ((buf (current-buffer))
3572         (actions message-exit-actions)
3573         (frame (selected-frame))
3574         (org-frame message-original-frame))
3575     (when (and (message-send arg)
3576                (buffer-name buf))
3577       (if message-kill-buffer-on-exit
3578           (kill-buffer buf)
3579         (bury-buffer buf)
3580         (when (eq buf (current-buffer))
3581           (message-bury buf)))
3582       (message-do-actions actions)
3583       (message-delete-frame frame org-frame)
3584       t)))
3585
3586 (defun message-dont-send ()
3587   "Don't send the message you have been editing.
3588 Instead, just auto-save the buffer and then bury it."
3589   (interactive)
3590   (set-buffer-modified-p t)
3591   (save-buffer)
3592   (let ((actions message-postpone-actions)
3593         (frame (selected-frame))
3594         (org-frame message-original-frame))
3595     (message-bury (current-buffer))
3596     (message-do-actions actions)
3597     (message-delete-frame frame org-frame)))
3598
3599 (defun message-kill-buffer ()
3600   "Kill the current buffer."
3601   (interactive)
3602   (when (or (not (buffer-modified-p))
3603             (eq t message-kill-buffer-query-function)
3604             (funcall message-kill-buffer-query-function
3605                      "The buffer modified; kill anyway? "))
3606     (let ((actions message-kill-actions)
3607           (draft-article message-draft-article)
3608           (auto-save-file-name buffer-auto-save-file-name)
3609           (file-name buffer-file-name)
3610           (modified (buffer-modified-p))
3611           (frame (selected-frame))
3612           (org-frame message-original-frame))
3613       (setq buffer-file-name nil)
3614       (kill-buffer (current-buffer))
3615       (when (and message-kill-buffer-and-remove-file
3616                  (or (and auto-save-file-name
3617                           (file-exists-p auto-save-file-name))
3618                      (and file-name
3619                           (file-exists-p file-name)))
3620                  (yes-or-no-p (format "Remove the backup file%s? "
3621                                       (if modified " too" ""))))
3622         (ignore-errors
3623           (delete-file auto-save-file-name))
3624         (let ((message-draft-article draft-article))
3625           (message-disassociate-draft)))
3626       (message-do-actions actions)
3627       (message-delete-frame frame org-frame)))
3628   (message ""))
3629
3630 (defun message-mimic-kill-buffer ()
3631   "Kill the current buffer with query.  This is an imitation for
3632 `kill-buffer', but it will delete a message frame."
3633   (interactive)
3634   (let ((bufname (read-buffer (format "Kill buffer: (default %s) "
3635                                       (buffer-name))))
3636         message-kill-buffer-and-remove-file)
3637     (when (or (not bufname)
3638               (string-equal bufname "")
3639               (string-equal bufname (buffer-name)))
3640       (message-kill-buffer))))
3641
3642 (defun message-delete-frame (frame org-frame)
3643   "Delete frame for editing message."
3644   (when (and (or (static-if (featurep 'xemacs)
3645                      (device-on-window-system-p)
3646                    window-system)
3647                  (>= emacs-major-version 20))
3648              (or (and (eq message-delete-frame-on-exit t)
3649                       (select-frame frame)
3650                       (or (eq frame org-frame)
3651                           (prog1
3652                               (y-or-n-p "Delete this frame?")
3653                             (message ""))))
3654                  (and (eq message-delete-frame-on-exit 'ask)
3655                       (select-frame frame)
3656                       (prog1
3657                           (y-or-n-p "Delete this frame?")
3658                         (message "")))))
3659     (delete-frame frame)))
3660
3661 (defun message-bury (buffer)
3662   "Bury this mail BUFFER."
3663   (let ((newbuf (other-buffer buffer)))
3664     (bury-buffer buffer)
3665     (if (and (fboundp 'frame-parameters)
3666              (cdr (assq 'dedicated (frame-parameters)))
3667              (not (null (delq (selected-frame) (visible-frame-list)))))
3668         (delete-frame (selected-frame))
3669       (switch-to-buffer newbuf))))
3670
3671 (defun message-send (&optional arg)
3672   "Send the message in the current buffer.
3673 If `message-interactive' is non-nil, wait for success indication or
3674 error messages, and inform user.
3675 Otherwise any failure is reported in a message back to the user from
3676 the mailer.
3677 The usage of ARG is defined by the instance that called Message.
3678 It should typically alter the sending method in some way or other."
3679   (interactive "P")
3680   ;; Disabled test.
3681   (when (or (buffer-modified-p)
3682             (message-check-element 'unchanged)
3683             (y-or-n-p "No changes in the buffer; really send? "))
3684     ;; Make it possible to undo the coming changes.
3685     (undo-boundary)
3686     (let ((inhibit-read-only t))
3687       (put-text-property (point-min) (point-max) 'read-only nil))
3688     (run-hooks 'message-send-hook)
3689     (message-fix-before-sending)
3690     (message message-sending-message)
3691     (let ((message-encoding-buffer
3692            (message-generate-new-buffer-clone-locals " message encoding"))
3693           (message-edit-buffer (current-buffer))
3694           (message-mime-mode mime-edit-mode-flag)
3695           (alist message-send-method-alist)
3696           (success t)
3697           elem sent dont-barf-on-no-method
3698           (message-options message-options))
3699       (unwind-protect
3700           (progn
3701             (message-options-set-recipient)
3702             (save-excursion
3703               (set-buffer message-encoding-buffer)
3704               (erase-buffer)
3705               ;; ;; Avoid copying text props (except hard newlines).
3706               ;; T-gnus change: copy all text props from the editing buffer
3707               ;; into the encoding buffer.
3708               (insert-buffer-substring message-edit-buffer)
3709               (funcall message-encode-function)
3710               (while (and success
3711                           (setq elem (pop alist)))
3712                 (when (funcall (cadr elem))
3713                   (when (and
3714                          (or (not (memq (car elem)
3715                                         message-sent-message-via))
3716                              (message-fetch-field "supersedes")
3717                              (if (or (message-gnksa-enable-p 'multiple-copies)
3718                                      (not (eq (car elem) 'news)))
3719                                  (y-or-n-p
3720                                   (format
3721                                    "Already sent message via %s; resend? "
3722                                    (car elem)))
3723                                (error "Denied posting -- multiple copies")))
3724                          (setq success (funcall (caddr elem) arg)))
3725                     (setq sent t)))))
3726             (unless
3727                 (or
3728                  sent
3729                  (not success)
3730                  (let ((fcc (message-fetch-field "Fcc"))
3731                        (gcc (message-fetch-field "Gcc")))
3732                    (when (or fcc gcc)
3733                      (or
3734                       (eq message-allow-no-recipients 'always)
3735                       (and (not (eq message-allow-no-recipients 'never))
3736                            (setq dont-barf-on-no-method
3737                                  (gnus-y-or-n-p
3738                                   (format "No receiver, perform %s anyway? "
3739                                           (cond ((and fcc gcc) "Fcc and Gcc")
3740                                                 (fcc "Fcc")
3741                                                 (t "Gcc"))))))))))
3742               (error "No methods specified to send by"))
3743             (when (or dont-barf-on-no-method
3744                       (and success sent))
3745               (message-do-fcc)
3746               (save-excursion
3747                 (run-hooks 'message-sent-hook))
3748               (message "Sending...done")
3749               ;; Mark the buffer as unmodified and delete auto-save.
3750               (set-buffer-modified-p nil)
3751               (delete-auto-save-file-if-necessary t)
3752               (message-disassociate-draft)
3753               ;; Delete other mail buffers and stuff.
3754               (message-do-send-housekeeping)
3755               (message-do-actions message-send-actions)
3756               ;; Return success.
3757               t))
3758         (kill-buffer message-encoding-buffer)))))
3759
3760 (defun message-send-via-mail (arg)
3761   "Send the current message via mail."
3762   (message-send-mail arg))
3763
3764 (defun message-send-via-news (arg)
3765   "Send the current message via news."
3766   (message-send-news arg))
3767
3768 (defmacro message-check (type &rest forms)
3769   "Eval FORMS if TYPE is to be checked."
3770   `(or (message-check-element ,type)
3771        (save-excursion
3772          ,@forms)))
3773
3774 (put 'message-check 'lisp-indent-function 1)
3775 (put 'message-check 'edebug-form-spec '(form body))
3776
3777 ;; Advise the function `invisible-region'.
3778 (let (current-load-list)
3779   (eval
3780    `(defadvice invisible-region (around add-mime-edit-invisible (start end)
3781                                         activate)
3782       "Advised by T-gnus Message.
3783 Add the text property `mime-edit-invisible' to an invisible text when
3784 the buffer's major mode is `message-mode'.  The added property will be
3785 used to distinguish whether the invisible text is a MIME part or not."
3786       ,(if (featurep 'xemacs)
3787            '(if (eq ?\n (char-after start))
3788                 (setq start (1+ start)))
3789          '(if (eq ?\n (char-after (1- end)))
3790               (setq end (1- end))))
3791       (setq ad-return-value
3792             (if (eq 'message-mode major-mode)
3793                 (add-text-properties start end
3794                                      '(invisible t mime-edit-invisible t))
3795               (put-text-property start end 'invisible t))))))
3796
3797 (defun message-text-with-property (prop)
3798   "Return a list of all points where the text has PROP."
3799   (let ((points nil)
3800         (point (point-min)))
3801     (save-excursion
3802       (while (< point (point-max))
3803         (when (get-text-property point prop)
3804           (push point points))
3805         (incf point)))
3806     (nreverse points)))
3807
3808 (defun message-fix-before-sending ()
3809   "Do various things to make the message nice before sending it."
3810   ;; Make sure there's a newline at the end of the message.
3811   (widen)
3812   (goto-char (point-max))
3813   (unless (bolp)
3814     (insert "\n"))
3815   ;; Make the hidden headers visible.
3816   (let ((points (message-text-with-property 'message-hidden)))
3817     (when points
3818       (goto-char (car points))
3819       (dolist (point points)
3820         (add-text-properties point (1+ point)
3821                              '(invisible nil intangible nil)))))
3822   ;; Make invisible text visible except for mime parts which may be
3823   ;; inserted by the MIME-Edit.
3824   ;; It doesn't seem as if this is useful, since the invisible property
3825   ;; is clobbered by an after-change hook anyhow.
3826   (message-check 'invisible-text
3827     ;; FIXME T-gnus: It should also detect invisible overlays.
3828     (let (from
3829           (to (point-min))
3830           mime-from mime-to hidden-start)
3831       (while (setq from (text-property-any to (point-max) 'invisible t))
3832         (setq to (or (text-property-not-all from (point-max) 'invisible t)
3833                      (point-max))
3834               mime-to from)
3835         (while (setq mime-from (text-property-any mime-to to
3836                                                   'mime-edit-invisible t))
3837           (when (> mime-from mime-to)
3838             (setq hidden-start (or hidden-start mime-to))
3839             (add-text-properties mime-to mime-from
3840                                  '(invisible nil face highlight
3841                                              font-lock-face highlight)))
3842           (setq mime-to (or (text-property-not-all mime-from to
3843                                                    'mime-edit-invisible t)
3844                             to)))
3845         (when (< mime-to to)
3846           (setq hidden-start (or hidden-start mime-to))
3847           (add-text-properties mime-to to
3848                                '(invisible nil face highlight
3849                                            font-lock-face highlight))))
3850       (when hidden-start
3851         (goto-char hidden-start)
3852         (set-window-start (selected-window) (gnus-point-at-bol))
3853         (unless (yes-or-no-p
3854                  "Invisible text found and made visible; continue sending? ")
3855           (error "Invisible text found and made visible")))))
3856 ;; The following check is needless to T-gnus since T-gnus determines
3857 ;; a MIME charset forcibly (even if it cannot be determined properly,
3858 ;; the value of the `default-mime-charset-for-write' variable is used).
3859 ;;  (message-check 'illegible-text
3860 ;;    (let ((mm-7bit-chars "\x20-\x7f\r\n\t\x7\x8\xb\xc\x1f\x1b")
3861 ;;        found choice)
3862 ;;      (message-goto-body)
3863 ;;      (skip-chars-forward mm-7bit-chars)
3864 ;;      (while (not (eobp))
3865 ;;      (when (let ((char (char-after)))
3866 ;;              (or (< (mm-char-int char) 128)
3867 ;;                  (and (mm-multibyte-p)
3868 ;;                       (> (length (mm-find-mime-charset-region
3869 ;;                                   (point) (point-max)))
3870 ;;                          1))))
3871 ;;        (message-overlay-put (message-make-overlay (point) (1+ (point)))
3872 ;;                             'face 'highlight)
3873 ;;        (setq found t))
3874 ;;      (forward-char)
3875 ;;      (skip-chars-forward mm-7bit-chars))
3876 ;;      (when found
3877 ;;      (setq choice
3878 ;;            (gnus-multiple-choice
3879 ;;             "Non-printable characters found.  Continue sending?"
3880 ;;             '((?d "Remove non-printable characters and send")
3881 ;;               (?r "Replace non-printable characters with dots and send")
3882 ;;               (?i "Ignore non-printable characters and send")
3883 ;;               (?e "Continue editing"))))
3884 ;;      (if (eq choice ?e)
3885 ;;        (error "Non-printable characters"))
3886 ;;      (message-goto-body)
3887 ;;      (skip-chars-forward mm-7bit-chars)
3888 ;;      (while (not (eobp))
3889 ;;        (when (let ((char (char-after)))
3890 ;;                (or (< (mm-char-int char) 128)
3891 ;;                    (and (mm-multibyte-p)
3892 ;;                         ;; Fixme: Wrong for Emacs 22 and for things
3893 ;;                         ;; like undecable utf-8.  Should at least
3894 ;;                         ;; use find-coding-systems-region.
3895 ;;                         (memq (char-charset char)
3896 ;;                               '(eight-bit-control eight-bit-graphic
3897 ;;                                                   control-1)))))
3898 ;;          (if (eq choice ?i)
3899 ;;              (message-kill-all-overlays)
3900 ;;            (delete-char 1)
3901 ;;            (when (eq choice ?r)
3902 ;;              (insert "."))))
3903 ;;        (forward-char)
3904 ;;        (skip-chars-forward mm-7bit-chars)))))
3905   )
3906
3907 (defun message-add-action (action &rest types)
3908   "Add ACTION to be performed when doing an exit of type TYPES."
3909   (while types
3910     (add-to-list (intern (format "message-%s-actions" (pop types)))
3911                  action)))
3912
3913 (defun message-delete-action (action &rest types)
3914   "Delete ACTION from lists of actions performed when doing an exit of type TYPES."
3915   (let (var)
3916     (while types
3917       (set (setq var (intern (format "message-%s-actions" (pop types))))
3918            (delq action (symbol-value var))))))
3919
3920 (defun message-do-actions (actions)
3921   "Perform all actions in ACTIONS."
3922   ;; Now perform actions on successful sending.
3923   (while actions
3924     (ignore-errors
3925       (cond
3926        ;; A simple function.
3927        ((functionp (car actions))
3928         (funcall (car actions)))
3929        ;; Something to be evaled.
3930        (t
3931         (eval (car actions)))))
3932     (pop actions)))
3933
3934 (defsubst message-maybe-split-and-send-mail ()
3935   "Split a message if necessary, and send it via mail.
3936 Returns nil if sending succeeded, returns any string if sending failed.
3937 This sub function is for exclusive use of `message-send-mail'."
3938   (let ((mime-edit-split-ignored-field-regexp
3939          mime-edit-split-ignored-field-regexp)
3940         (case-fold-search t)
3941         failure)
3942     (while (string-match "Message-ID" mime-edit-split-ignored-field-regexp)
3943       (setq mime-edit-split-ignored-field-regexp
3944             (concat (substring mime-edit-split-ignored-field-regexp
3945                                0 (match-beginning 0))
3946                     "Hey_MIME-Edit,_there_is_an_inviolable_Message_ID"
3947                     "_so_don't_rape_it!"
3948                     (substring mime-edit-split-ignored-field-regexp
3949                                (match-end 0)))))
3950     (setq failure
3951           (or
3952            (catch 'message-sending-mail-failure
3953              (mime-edit-maybe-split-and-send
3954               (function
3955                (lambda ()
3956                  (interactive)
3957                  (save-restriction
3958                    (std11-narrow-to-header mail-header-separator)
3959                    (goto-char (point-min))
3960                    (when (re-search-forward "^Message-ID:" nil t)
3961                      (delete-region (match-end 0) (std11-field-end))
3962                      (insert " " (message-make-message-id))))
3963                  (condition-case err
3964                      (funcall (or message-send-mail-real-function
3965                                   message-send-mail-function))
3966                    (error
3967                     (throw 'message-sending-mail-failure err))))))
3968              nil)
3969            (condition-case err
3970                (progn
3971                  (funcall (or message-send-mail-real-function
3972                               message-send-mail-function))
3973                  nil)
3974              (error err))))
3975     (when failure
3976       (if (eq 'error (car failure))
3977           (cadr failure)
3978         (prin1-to-string failure)))))
3979
3980 (defun message-send-mail-partially ()
3981   "Send mail as message/partial."
3982   ;; replace the header delimiter with a blank line
3983   (goto-char (point-min))
3984   (re-search-forward
3985    (concat "^" (regexp-quote mail-header-separator) "\n"))
3986   (replace-match "\n")
3987   (run-hooks 'message-send-mail-hook)
3988   (let ((p (goto-char (point-min)))
3989         (tembuf (message-generate-new-buffer-clone-locals " message temp"))
3990         (curbuf (current-buffer))
3991         (id (message-make-message-id)) (n 1)
3992         plist total  header required-mail-headers)
3993     (while (not (eobp))
3994       (if (< (point-max) (+ p message-send-mail-partially-limit))
3995           (goto-char (point-max))
3996         (goto-char (+ p message-send-mail-partially-limit))
3997         (beginning-of-line)
3998         (if (<= (point) p) (forward-line 1))) ;; In case of bad message.
3999       (push p plist)
4000       (setq p (point)))
4001     (setq total (length plist))
4002     (push (point-max) plist)
4003     (setq plist (nreverse plist))
4004     (unwind-protect
4005         (save-excursion
4006           (setq p (pop plist))
4007           (while plist
4008             (set-buffer curbuf)
4009             (copy-to-buffer tembuf p (car plist))
4010             (set-buffer tembuf)
4011             (goto-char (point-min))
4012             (if header
4013                 (progn
4014                   (goto-char (point-min))
4015                   (narrow-to-region (point) (point))
4016                   (insert header))
4017               (message-goto-eoh)
4018               (setq header (buffer-substring (point-min) (point)))
4019               (goto-char (point-min))
4020               (narrow-to-region (point) (point))
4021               (insert header)
4022               (message-remove-header "Mime-Version")
4023               (message-remove-header "Content-Type")
4024               (message-remove-header "Content-Transfer-Encoding")
4025               (message-remove-header "Message-ID")
4026               (message-remove-header "Lines")
4027               (goto-char (point-max))
4028               (insert "Mime-Version: 1.0\n")
4029               (setq header (buffer-string)))
4030             (goto-char (point-max))
4031             (insert (format "Content-Type: message/partial; id=\"%s\"; number=%d; total=%d\n\n"
4032                             id n total))
4033             (forward-char -1)
4034             (let ((mail-header-separator ""))
4035               (when (memq 'Message-ID message-required-mail-headers)
4036                 (insert "Message-ID: " (message-make-message-id) "\n"))
4037               (when (memq 'Lines message-required-mail-headers)
4038                 (insert "Lines: " (message-make-lines) "\n"))
4039               (message-goto-subject)
4040               (end-of-line)
4041               (insert (format " (%d/%d)" n total))
4042               (widen)
4043               (mm-with-unibyte-current-buffer
4044                 (funcall (or message-send-mail-real-function
4045                              message-send-mail-function))))
4046             (setq n (+ n 1))
4047             (setq p (pop plist))
4048             (erase-buffer)))
4049       (kill-buffer tembuf))))
4050
4051 (defun message-send-mail (&optional arg)
4052   (require 'mail-utils)
4053   (let* ((tembuf (message-generate-new-buffer-clone-locals " message temp"))
4054          (case-fold-search nil)
4055          (news (message-news-p))
4056          (message-this-is-mail t)
4057          (headers message-required-mail-headers)
4058          failure)
4059     (save-restriction
4060       (message-narrow-to-headers)
4061       ;; Generate the Mail-Followup-To header if the header is not there...
4062       (if (and (message-subscribed-p)
4063                (not (mail-fetch-field "mail-followup-to")))
4064           (setq headers
4065                 (cons
4066                  (cons "Mail-Followup-To" (message-make-mail-followup-to))
4067                  message-required-mail-headers))
4068         ;; otherwise, delete the MFT header if the field is empty
4069         (when (equal "" (mail-fetch-field "mail-followup-to"))
4070           (message-remove-header "^Mail-Followup-To:")))
4071       ;; Insert some headers.
4072       (let ((message-deletable-headers
4073              (if news nil message-deletable-headers)))
4074         (message-generate-headers headers))
4075       ;; Let the user do all of the above.
4076       (run-hooks 'message-header-hook))
4077     (if (not (message-check-mail-syntax))
4078         (progn
4079           (message "")
4080           nil)
4081       (unwind-protect
4082           (save-excursion
4083             (set-buffer tembuf)
4084             (erase-buffer)
4085             ;; ;; Avoid copying text props (except hard newlines).
4086             ;; T-gnus change: copy all text props from the editing buffer
4087             ;; into the encoding buffer.
4088             (insert-buffer-substring message-encoding-buffer)
4089             ;; Remove some headers.
4090             (save-restriction
4091               (message-narrow-to-headers)
4092 ;; We Semi-gnus people have no use for it.
4093 ;;            ;; We (re)generate the Lines header.
4094 ;;            (when (memq 'Lines message-required-mail-headers)
4095 ;;              (message-generate-headers '(Lines)))
4096               (message-remove-header message-ignored-mail-headers t))
4097             (goto-char (point-max))
4098             ;; require one newline at the end.
4099             (or (= (preceding-char) ?\n)
4100                 (insert ?\n))
4101             (message-cleanup-headers)
4102             ;; FIXME: we're inserting the courtesy copy after encoding.
4103             ;; This is wrong if the courtesy copy string contains
4104             ;; non-ASCII characters. -- jh
4105             (when
4106                 (save-restriction
4107                   (message-narrow-to-headers)
4108                   (and news
4109                        (or (message-fetch-field "cc")
4110                            (message-fetch-field "bcc")
4111                            (message-fetch-field "to"))
4112                        (let ((content-type (mime-read-Content-Type)))
4113                          (and
4114                           (or
4115                            (not content-type)
4116                            (and
4117                             (eq 'text (cdr (assq 'type content-type)))
4118                             (eq 'plain (cdr (assq 'subtype content-type)))))
4119                           (not
4120                            (string= "base64"
4121                                     (mime-read-Content-Transfer-Encoding)))))))
4122               (message-insert-courtesy-copy))
4123             (setq failure (message-maybe-split-and-send-mail)))
4124         (kill-buffer tembuf))
4125       (set-buffer message-edit-buffer)
4126       (if failure
4127           (progn
4128             (message "Couldn't send message via mail: %s" failure)
4129             nil)
4130         (push 'mail message-sent-message-via)))))
4131
4132 (defun message-send-mail-with-sendmail ()
4133   "Send off the prepared buffer with sendmail."
4134   (let ((errbuf (if message-interactive
4135                     (message-generate-new-buffer-clone-locals
4136                      " sendmail errors")
4137                   0))
4138         resend-to-addresses delimline)
4139     (unwind-protect
4140         (progn
4141           (let ((case-fold-search t))
4142             (save-restriction
4143               (message-narrow-to-headers)
4144               (setq resend-to-addresses (message-fetch-field "resent-to")))
4145             ;; Change header-delimiter to be what sendmail expects.
4146             (goto-char (point-min))
4147             (re-search-forward
4148              (concat "^" (regexp-quote mail-header-separator) "\n"))
4149             (replace-match "\n")
4150             (backward-char 1)
4151             (setq delimline (point-marker))
4152             (run-hooks 'message-send-mail-hook)
4153             ;; Insert an extra newline if we need it to work around
4154             ;; Sun's bug that swallows newlines.
4155             (goto-char (1+ delimline))
4156             (when (eval message-mailer-swallows-blank-line)
4157               (newline))
4158             (when message-interactive
4159               (save-excursion
4160                 (set-buffer errbuf)
4161                 (erase-buffer))))
4162           (let* ((default-directory "/")
4163                  (cpr (as-binary-process
4164                        (apply
4165                         'call-process-region
4166                         (append
4167                          (list (point-min) (point-max)
4168                                (if (boundp 'sendmail-program)
4169                                    sendmail-program
4170                                  "/usr/lib/sendmail")
4171                                nil errbuf nil "-oi")
4172                          ;; Always specify who from,
4173                          ;; since some systems have broken sendmails.
4174                          ;; But some systems are more broken with -f, so
4175                          ;; we'll let users override this.
4176                          (if (null message-sendmail-f-is-evil)
4177                              (list "-f" (message-sendmail-envelope-from)))
4178                          ;; These mean "report errors by mail"
4179                          ;; and "deliver in background".
4180                          (if (null message-interactive) '("-oem" "-odb"))
4181                          ;; Get the addresses from the message
4182                          ;; unless this is a resend.
4183                          ;; We must not do that for a resend
4184                          ;; because we would find the original addresses.
4185                          ;; For a resend, include the specific addresses.
4186                          (if resend-to-addresses
4187                              (list resend-to-addresses)
4188                            '("-t")))))))
4189             (unless (or (null cpr) (and (numberp cpr) (zerop cpr)))
4190               (error "Sending...failed with exit value %d" cpr)))
4191           (when message-interactive
4192             (save-excursion
4193               (set-buffer errbuf)
4194               (goto-char (point-min))
4195               (while (re-search-forward "\n\n* *" nil t)
4196                 (replace-match "; "))
4197               (if (not (zerop (buffer-size)))
4198                   (error "Sending...failed to %s"
4199                          (buffer-string))))))
4200       (when (bufferp errbuf)
4201         (kill-buffer errbuf)))))
4202
4203 (defun message-send-mail-with-qmail ()
4204   "Pass the prepared message buffer to qmail-inject.
4205 Refer to the documentation for the variable `message-send-mail-function'
4206 to find out how to use this."
4207   ;; replace the header delimiter with a blank line
4208   (goto-char (point-min))
4209   (re-search-forward
4210    (concat "^" (regexp-quote mail-header-separator) "\n"))
4211   (replace-match "\n")
4212   (backward-char 1)
4213   (run-hooks 'message-send-mail-hook)
4214   ;; send the message
4215   (case
4216       (as-binary-process
4217        (apply
4218         'call-process-region 1 (point-max) message-qmail-inject-program
4219         nil nil nil
4220         ;; qmail-inject's default behaviour is to look for addresses on the
4221         ;; command line; if there're none, it scans the headers.
4222         ;; yes, it does The Right Thing w.r.t. Resent-To and it's kin.
4223         ;;
4224         ;; in general, ALL of qmail-inject's defaults are perfect for simply
4225         ;; reading a formatted (i. e., at least a To: or Resent-To header)
4226         ;; message from stdin.
4227         ;;
4228         ;; qmail also has the advantage of not having been raped by
4229         ;; various vendors, so we don't have to allow for that, either --
4230         ;; compare this with message-send-mail-with-sendmail and weep
4231         ;; for sendmail's lost innocence.
4232         ;;
4233         ;; all this is way cool coz it lets us keep the arguments entirely
4234         ;; free for -inject-arguments -- a big win for the user and for us
4235         ;; since we don't have to play that double-guessing game and the user
4236         ;; gets full control (no gestapo'ish -f's, for instance).  --sj
4237         (if (functionp message-qmail-inject-args)
4238             (funcall message-qmail-inject-args)
4239           message-qmail-inject-args)))
4240     ;; qmail-inject doesn't say anything on it's stdout/stderr,
4241     ;; we have to look at the retval instead
4242     (0 nil)
4243     (100 (error "qmail-inject reported permanent failure"))
4244     (111 (error "qmail-inject reported transient failure"))
4245     ;; should never happen
4246     (t   (error "qmail-inject reported unknown failure"))))
4247
4248 (defun message-send-mail-with-mh ()
4249   "Send the prepared message buffer with mh."
4250   (let ((mh-previous-window-config nil)
4251         (name (mh-new-draft-name)))
4252     (setq buffer-file-name name)
4253     ;; MH wants to generate these headers itself.
4254     (when message-mh-deletable-headers
4255       (let ((headers message-mh-deletable-headers))
4256         (while headers
4257           (goto-char (point-min))
4258           (and (re-search-forward
4259                 (concat "^" (symbol-name (car headers)) ": *") nil t)
4260                (message-delete-line))
4261           (pop headers))))
4262     (run-hooks 'message-send-mail-hook)
4263     ;; Pass it on to mh.
4264     (mh-send-letter)))
4265
4266 (defun message-send-mail-with-smtp ()
4267   "Send off the prepared buffer with SMTP."
4268   (require 'smtp) ; XXX
4269   (let ((case-fold-search t)
4270         recipients)
4271     (save-restriction
4272       (message-narrow-to-headers)
4273       (setq recipients
4274             ;; XXX: Should be replaced by better one.
4275             (smtp-deduce-address-list (current-buffer)
4276                                       (point-min) (point-max)))
4277       ;; Remove BCC lines.
4278       (message-remove-header "bcc"))
4279     ;; replace the header delimiter with a blank line.
4280     (goto-char (point-min))
4281     (re-search-forward
4282      (concat "^" (regexp-quote mail-header-separator) "\n"))
4283     (replace-match "\n")
4284     (backward-char 1)
4285     (run-hooks 'message-send-mail-hook)
4286     (if recipients
4287         (smtp-send-buffer user-mail-address recipients (current-buffer))
4288       (error "Sending failed; no recipients"))))
4289
4290 (defsubst message-maybe-split-and-send-news (method)
4291   "Split a message if necessary, and send it via news.
4292 Returns nil if sending succeeded, returns t if sending failed.
4293 This sub function is for exclusive use of `message-send-news'."
4294   (let ((mime-edit-split-ignored-field-regexp
4295          mime-edit-split-ignored-field-regexp)
4296         (case-fold-search t))
4297     (while (string-match "Message-ID" mime-edit-split-ignored-field-regexp)
4298       (setq mime-edit-split-ignored-field-regexp
4299             (concat (substring mime-edit-split-ignored-field-regexp
4300                                0 (match-beginning 0))
4301                     "Hey_MIME-Edit,_there_is_an_inviolable_Message_ID"
4302                     "_so_don't_rape_it!"
4303                     (substring mime-edit-split-ignored-field-regexp
4304                                (match-end 0)))))
4305     (or
4306      (catch 'message-sending-news-failure
4307        (mime-edit-maybe-split-and-send
4308         (function
4309          (lambda ()
4310            (interactive)
4311            (save-restriction
4312              (std11-narrow-to-header mail-header-separator)
4313              (goto-char (point-min))
4314              (when (re-search-forward "^Message-ID:" nil t)
4315                (delete-region (match-end 0) (std11-field-end))
4316                (insert " " (message-make-message-id))))
4317            (unless (funcall message-send-news-function method)
4318              (throw 'message-sending-news-failure t)))))
4319        nil)
4320      (not (funcall message-send-news-function method)))))
4321
4322 (defun message-smtpmail-send-it ()
4323   "Send the prepared message buffer with `smtpmail-send-it'.
4324 This only differs from `smtpmail-send-it' that this command evaluates
4325 `message-send-mail-hook' just before sending a message.  It is useful
4326 if your ISP requires the POP-before-SMTP authentication.  See the
4327 documentation for the function `mail-source-touch-pop'."
4328   (run-hooks 'message-send-mail-hook)
4329   (smtpmail-send-it))
4330
4331 (defun message-canlock-generate ()
4332   "Return a string that is non-trivial to guess.
4333 Do not use this for anything important, it is cryptographically weak."
4334   (let (sha1-maximum-internal-length)
4335     (sha1 (concat (message-unique-id)
4336                   (format "%x%x%x" (random) (random t) (random))
4337                   (prin1-to-string (recent-keys))
4338                   (prin1-to-string (garbage-collect))))))
4339
4340 (defun message-canlock-password ()
4341   "The password used by message for cancel locks.
4342 This is the value of `canlock-password', if that option is non-nil.
4343 Otherwise, generate and save a value for `canlock-password' first."
4344   (unless canlock-password
4345     (customize-save-variable 'canlock-password (message-canlock-generate))
4346     (setq canlock-password-for-verify canlock-password))
4347   canlock-password)
4348
4349 (defun message-insert-canlock ()
4350   (when message-insert-canlock
4351     (message-canlock-password)
4352     (canlock-insert-header)))
4353
4354 (defun message-send-news (&optional arg)
4355   (let* ((tembuf (message-generate-new-buffer-clone-locals " *message temp*"))
4356          (case-fold-search nil)
4357          (method (if (functionp message-post-method)
4358                      (funcall message-post-method arg)
4359                    message-post-method))
4360          (newsgroups-field (save-restriction
4361                              (message-narrow-to-headers-or-head)
4362                              (message-fetch-field "Newsgroups")))
4363          (followup-field (save-restriction
4364                            (message-narrow-to-headers-or-head)
4365                            (message-fetch-field "Followup-To")))
4366          ;; BUG: We really need to get the charset for each name in the
4367          ;; Newsgroups and Followup-To lines to allow crossposting
4368          ;; between group namess with incompatible character sets.
4369          ;; -- Per Abrahamsen <abraham@dina.kvl.dk> 2001-10-08.
4370          (group-field-charset
4371           (gnus-group-name-charset method newsgroups-field))
4372          (followup-field-charset
4373           (gnus-group-name-charset method (or followup-field "")))
4374          (mime-field-encoding-method-alist
4375           (append (when group-field-charset
4376                     (list (cons "Newsgroups" group-field-charset)))
4377                   (when followup-field-charset
4378                     (list (cons "Followup-To" followup-field-charset)))
4379                   mime-field-encoding-method-alist))
4380          (message-syntax-checks
4381           (if (and arg
4382                    (listp message-syntax-checks))
4383               (cons '(existing-newsgroups . disabled)
4384                     message-syntax-checks)
4385             message-syntax-checks))
4386          (message-this-is-news t)
4387          result)
4388     (save-restriction
4389       (message-narrow-to-headers)
4390       ;; Insert some headers.
4391       (message-generate-headers message-required-news-headers)
4392       (message-insert-canlock)
4393       ;; Let the user do all of the above.
4394       (run-hooks 'message-header-hook))
4395     ;; Note: This check will be disabled by the ".*" default value for
4396     ;; gnus-group-name-charset-group-alist. -- Pa 2001-10-07.
4397     (when (and group-field-charset
4398                (listp message-syntax-checks))
4399       (setq message-syntax-checks
4400             (cons '(valid-newsgroups . disabled)
4401                   message-syntax-checks)))
4402     (message-cleanup-headers)
4403     (if (not (let ((message-post-method method))
4404                (message-check-news-syntax)))
4405         nil
4406       (unwind-protect
4407           (save-excursion
4408             (set-buffer tembuf)
4409             (buffer-disable-undo)
4410             (erase-buffer)
4411             (insert-buffer-substring message-encoding-buffer)
4412             ;; Remove some headers.
4413             (save-restriction
4414               (message-narrow-to-headers)
4415 ;; We Semi-gnus people have no use for it.
4416 ;;            ;; We (re)generate the Lines header.
4417 ;;            (when (memq 'Lines message-required-mail-headers)
4418 ;;              (message-generate-headers '(Lines)))
4419               ;; Remove some headers.
4420               (message-remove-header message-ignored-news-headers t))
4421             (goto-char (point-max))
4422             ;; require one newline at the end.
4423             (or (= (preceding-char) ?\n)
4424                 (insert ?\n))
4425             (setq result (message-maybe-split-and-send-news method)))
4426         (kill-buffer tembuf))
4427       (set-buffer message-edit-buffer)
4428       (if result
4429           (progn
4430             (message "Couldn't send message via news: %s"
4431                      (nnheader-get-report (car method)))
4432             nil)
4433         (push 'news message-sent-message-via)))))
4434
4435 ;; 1997-09-29 by MORIOKA Tomohiko
4436 (defun message-send-news-with-gnus (method)
4437   (let ((case-fold-search t))
4438     ;; Remove the delimiter.
4439     (goto-char (point-min))
4440     (re-search-forward
4441      (concat "^" (regexp-quote mail-header-separator) "\n"))
4442     (replace-match "\n")
4443     (backward-char 1)
4444     (run-hooks 'message-send-news-hook)
4445     (gnus-open-server method)
4446     (message "Sending news via %s..." (gnus-server-string method))
4447     (gnus-request-post method)
4448     ))
4449
4450 ;;;
4451 ;;; Header generation & syntax checking.
4452 ;;;
4453
4454 (defun message-check-element (type)
4455   "Return non-nil if this TYPE is not to be checked."
4456   (if (eq message-syntax-checks 'dont-check-for-anything-just-trust-me)
4457       t
4458     (let ((able (assq type message-syntax-checks)))
4459       (and (consp able)
4460            (eq (cdr able) 'disabled)))))
4461
4462 (defun message-check-news-syntax ()
4463   "Check the syntax of the message."
4464   (save-excursion
4465     (save-restriction
4466       (widen)
4467       (and
4468        ;; We narrow to the headers and check them first.
4469        (save-excursion
4470          (save-restriction
4471            (message-narrow-to-headers)
4472            (message-check-news-header-syntax)))
4473        ;; Check the body.
4474        (save-excursion
4475          (set-buffer message-edit-buffer)
4476          (message-check-news-body-syntax))))))
4477
4478 (defun message-check-news-header-syntax ()
4479   (and
4480    ;; Check Newsgroups header.
4481    (message-check 'newsgroups
4482      (let ((group (message-fetch-field "newsgroups")))
4483        (or
4484         (and group
4485              (not (string-match "\\`[ \t]*\\'" group)))
4486         (ignore
4487          (message
4488           "The newsgroups field is empty or missing.  Posting is denied.")))))
4489    ;; Check the Subject header.
4490    (message-check 'subject
4491      (let* ((case-fold-search t)
4492             (subject (message-fetch-field "subject")))
4493        (or
4494         (and subject
4495              (not (string-match "\\`[ \t]*\\'" subject)))
4496         (ignore
4497          (message
4498           "The subject field is empty or missing.  Posting is denied.")))))
4499    ;; Check for commands in Subject.
4500    (message-check 'subject-cmsg
4501      (if (string-match "^cmsg " (message-fetch-field "subject"))
4502          (y-or-n-p
4503           "The control code \"cmsg\" is in the subject.  Really post? ")
4504        t))
4505    ;; Check long header lines.
4506    (message-check 'long-header-lines
4507      (let ((start (point))
4508            (header nil)
4509            (length 0)
4510            found)
4511        (while (and (not found)
4512                    (re-search-forward "^\\([^ \t:]+\\): " nil t))
4513          (if (> (- (point) (match-beginning 0)) 998)
4514              (setq found t
4515                    length (- (point) (match-beginning 0)))
4516            (setq header (match-string-no-properties 1)))
4517          (setq start (match-beginning 0))
4518          (forward-line 1))
4519        (if found
4520            (y-or-n-p (format "Your %s header is too long (%d).  Really post? "
4521                              header length))
4522          t)))
4523    ;; Check for multiple identical headers.
4524    (message-check 'multiple-headers
4525      (let (found)
4526        (while (and (not found)
4527                    (re-search-forward "^[^ \t:]+: " nil t))
4528          (save-excursion
4529            (or (re-search-forward
4530                 (concat "^"
4531                         (regexp-quote
4532                          (setq found
4533                                (buffer-substring
4534                                 (match-beginning 0) (- (match-end 0) 2))))
4535                         ":")
4536                 nil t)
4537                (setq found nil))))
4538        (if found
4539            (y-or-n-p (format "Multiple %s headers.  Really post? " found))
4540          t)))
4541    ;; Check for Version and Sendsys.
4542    (message-check 'sendsys
4543      (if (re-search-forward "^Sendsys:\\|^Version:" nil t)
4544          (y-or-n-p
4545           (format "The article contains a %s command.  Really post? "
4546                   (buffer-substring (match-beginning 0)
4547                                     (1- (match-end 0)))))
4548        t))
4549    ;; See whether we can shorten Followup-To.
4550    (message-check 'shorten-followup-to
4551      (let ((newsgroups (message-fetch-field "newsgroups"))
4552            (followup-to (message-fetch-field "followup-to"))
4553            to)
4554        (when (and newsgroups
4555                   (string-match "," newsgroups)
4556                   (not followup-to)
4557                   (not
4558                    (zerop
4559                     (length
4560                      (setq to (completing-read
4561                                "Followups to (default: no Followup-To header) "
4562                                (mapcar #'list
4563                                        (cons "poster"
4564                                              (message-tokenize-header
4565                                               newsgroups)))))))))
4566          (goto-char (point-min))
4567          (insert "Followup-To: " to "\n"))
4568        t))
4569    ;; Check "Shoot me".
4570    (message-check 'shoot
4571      (if (re-search-forward
4572           "Message-ID.*.i-did-not-set--mail-host-address--so-tickle-me" nil t)
4573          (y-or-n-p "You appear to have a misconfigured system.  Really post? ")
4574        t))
4575    ;; Check for Approved.
4576    (message-check 'approved
4577      (if (re-search-forward "^Approved:" nil t)
4578          (y-or-n-p "The article contains an Approved header.  Really post? ")
4579        t))
4580    ;; Check the Message-ID header.
4581    (message-check 'message-id
4582      (let* ((case-fold-search t)
4583             (message-id (message-fetch-field "message-id" t)))
4584        (or (not message-id)
4585            ;; Is there an @ in the ID?
4586            (and (string-match "@" message-id)
4587                 ;; Is there a dot in the ID?
4588                 (string-match "@[^.]*\\." message-id)
4589                 ;; Does the ID end with a dot?
4590                 (not (string-match "\\.>" message-id)))
4591            (y-or-n-p
4592             (format "The Message-ID looks strange: \"%s\".  Really post? "
4593                     message-id)))))
4594    ;; Check the Newsgroups & Followup-To headers.
4595    (message-check 'existing-newsgroups
4596      (let* ((case-fold-search t)
4597             (newsgroups (message-fetch-field "newsgroups"))
4598             (followup-to (message-fetch-field "followup-to"))
4599             (groups (message-tokenize-header
4600                      (if followup-to
4601                          (concat newsgroups "," followup-to)
4602                        newsgroups)))
4603             (post-method (if (functionp message-post-method)
4604                              (funcall message-post-method)
4605                            message-post-method))
4606             ;; KLUDGE to handle nnvirtual groups.  Doing this right
4607             ;; would probably involve a new nnoo function.
4608             ;; -- Per Abrahamsen <abraham@dina.kvl.dk>, 2001-10-17.
4609             (method (if (and (consp post-method)
4610                              (eq (car post-method) 'nnvirtual)
4611                              gnus-message-group-art)
4612                         (let ((group (car (nnvirtual-find-group-art
4613                                            (car gnus-message-group-art)
4614                                            (cdr gnus-message-group-art)))))
4615                           (gnus-find-method-for-group group))
4616                       post-method))
4617             (known-groups
4618              (mapcar (lambda (n)
4619                        (gnus-group-name-decode
4620                         (gnus-group-real-name n)
4621                         (gnus-group-name-charset method n)))
4622                      (gnus-groups-from-server method)))
4623             errors)
4624        (while groups
4625          (when (and (not (equal (car groups) "poster"))
4626                     (not (member (car groups) known-groups))
4627                     (not (member (car groups) errors)))
4628            (push (car groups) errors))
4629          (pop groups))
4630        (cond
4631         ;; Gnus is not running.
4632         ((or (not (and (boundp 'gnus-active-hashtb)
4633                        gnus-active-hashtb))
4634              (not (boundp 'gnus-read-active-file)))
4635          t)
4636         ;; We don't have all the group names.
4637         ((and (or (not gnus-read-active-file)
4638                   (eq gnus-read-active-file 'some))
4639               errors)
4640          (y-or-n-p
4641           (format
4642            "Really use %s possibly unknown group%s: %s? "
4643            (if (= (length errors) 1) "this" "these")
4644            (if (= (length errors) 1) "" "s")
4645            (mapconcat 'identity errors ", "))))
4646         ;; There were no errors.
4647         ((not errors)
4648          t)
4649         ;; There are unknown groups.
4650         (t
4651          (y-or-n-p
4652           (format
4653            "Really post to %s unknown group%s: %s? "
4654            (if (= (length errors) 1) "this" "these")
4655            (if (= (length errors) 1) "" "s")
4656            (mapconcat 'identity errors ", ")))))))
4657    ;; Check continuation headers.
4658    (message-check 'continuation-headers
4659      (goto-char (point-min))
4660      (let ((do-posting t))
4661        (while (re-search-forward "^[^ \t\n][^:\n]*$" nil t)
4662          (if (y-or-n-p "Fix continuation lines? ")
4663              (progn
4664                (goto-char (match-beginning 0))
4665                (insert " "))
4666            (unless (y-or-n-p "Send anyway? ")
4667              (setq do-posting nil))))
4668        do-posting))
4669    ;; Check the Newsgroups & Followup-To headers for syntax errors.
4670    (message-check 'valid-newsgroups
4671      (let ((case-fold-search t)
4672            (headers '("Newsgroups" "Followup-To"))
4673            header error)
4674        (while (and headers (not error))
4675          (when (setq header (mail-fetch-field (car headers)))
4676            (if (or
4677                 (not
4678                  (string-match
4679                   "\\`\\([-+_&.a-zA-Z0-9]+\\)?\\(,[-+_&.a-zA-Z0-9]+\\)*\\'"
4680                   header))
4681                 (memq
4682                  nil (mapcar
4683                       (lambda (g)
4684                         (not (string-match "\\.\\'\\|\\.\\." g)))
4685                       (message-tokenize-header header ","))))
4686                (setq error t)))
4687          (unless error
4688            (pop headers)))
4689        (if (not error)
4690            t
4691          (y-or-n-p
4692           (format "The %s header looks odd: \"%s\".  Really post? "
4693                   (car headers) header)))))
4694    (message-check 'repeated-newsgroups
4695      (let ((case-fold-search t)
4696            (headers '("Newsgroups" "Followup-To"))
4697            header error groups group)
4698        (while (and headers
4699                    (not error))
4700          (when (setq header (mail-fetch-field (pop headers)))
4701            (setq groups (message-tokenize-header header ","))
4702            (while (setq group (pop groups))
4703              (when (member group groups)
4704                (setq error group
4705                      groups nil)))))
4706        (if (not error)
4707            t
4708          (y-or-n-p
4709           (format "Group %s is repeated in headers.  Really post? " error)))))
4710    ;; Check the From header.
4711    (message-check 'from
4712      (let* ((case-fold-search t)
4713             (from (message-fetch-field "from"))
4714             ad)
4715        (cond
4716         ((not from)
4717          (message "There is no From line.  Posting is denied.")
4718          nil)
4719         ((or (not (string-match
4720                    "@[^\\.]*\\."
4721                    (setq ad (nth 1 (std11-extract-address-components
4722                                     from))))) ;larsi@ifi
4723              (string-match "\\.\\." ad) ;larsi@ifi..uio
4724              (string-match "@\\." ad)   ;larsi@.ifi.uio
4725              (string-match "\\.$" ad)   ;larsi@ifi.uio.
4726              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
4727              (string-match "(.*).*(.*)" from)) ;(lars) (lars)
4728          (message
4729           "Denied posting -- the From looks strange: \"%s\"." from)
4730          nil)
4731         ((let ((addresses (rfc822-addresses from)))
4732            (while (and addresses
4733                        (not (eq (string-to-char (car addresses)) ?\()))
4734              (setq addresses (cdr addresses)))
4735            addresses)
4736          (message
4737           "Denied posting -- bad From address: \"%s\"." from)
4738          nil)
4739         (t t))))
4740    ;; Check the Reply-To header.
4741    (message-check 'reply-to
4742      (let* ((case-fold-search t)
4743             (reply-to (message-fetch-field "reply-to"))
4744             ad)
4745        (cond
4746         ((not reply-to)
4747          t)
4748         ((string-match "," reply-to)
4749          (y-or-n-p
4750           (format "Multiple Reply-To addresses: \"%s\". Really post? "
4751                   reply-to)))
4752         ((or (not (string-match
4753                    "@[^\\.]*\\."
4754                    (setq ad (nth 1 (std11-extract-address-components
4755                                     reply-to))))) ;larsi@ifi
4756              (string-match "\\.\\." ad) ;larsi@ifi..uio
4757              (string-match "@\\." ad)   ;larsi@.ifi.uio
4758              (string-match "\\.$" ad)   ;larsi@ifi.uio.
4759              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
4760              (string-match "(.*).*(.*)" reply-to)) ;(lars) (lars)
4761          (y-or-n-p
4762           (format
4763            "The Reply-To looks strange: \"%s\". Really post? "
4764            reply-to)))
4765         (t t))))))
4766
4767 (defun message-check-news-body-syntax ()
4768   (and
4769    ;; Check for long lines.
4770    (message-check 'long-lines
4771      (goto-char (point-min))
4772      (re-search-forward
4773       (concat "^" (regexp-quote mail-header-separator) "$"))
4774      (forward-line 1)
4775      (while (and
4776              (or (looking-at
4777                   mime-edit-tag-regexp)
4778                  (let ((p (point)))
4779                    (end-of-line)
4780                    (< (- (point) p) 80)))
4781              (zerop (forward-line 1))))
4782      (or (bolp)
4783          (eobp)
4784          (y-or-n-p
4785           "You have lines longer than 79 characters.  Really post? ")))
4786    ;; Check whether the article is empty.
4787    (message-check 'empty
4788      (goto-char (point-min))
4789      (re-search-forward
4790       (concat "^" (regexp-quote mail-header-separator) "$"))
4791      (forward-line 1)
4792      (let ((b (point)))
4793        (goto-char (point-max))
4794        (re-search-backward message-signature-separator nil t)
4795        (beginning-of-line)
4796        (or (re-search-backward "[^ \n\t]" b t)
4797            (if (message-gnksa-enable-p 'empty-article)
4798                (y-or-n-p "Empty article.  Really post? ")
4799              (message "Denied posting -- Empty article.")
4800              nil))))
4801    ;; Check for control characters.
4802    (message-check 'control-chars
4803      (if (re-search-forward "[\000-\007\013\015-\032\034-\037\200-\237]" nil t)
4804          (y-or-n-p
4805           "The article contains control characters.  Really post? ")
4806        t))
4807    ;; Check 8bit characters.
4808    (message-check '8bit
4809      (message-check-8bit))
4810    ;; Check excessive size.
4811    (message-check 'size
4812      (if (> (buffer-size) 60000)
4813          (y-or-n-p
4814           (format "The article is %d octets long.  Really post? "
4815                   (buffer-size)))
4816        t))
4817    ;; Check whether any new text has been added.
4818    (message-check 'new-text
4819      (or
4820       (not message-checksum)
4821       (not (eq (message-checksum) message-checksum))
4822       (if (message-gnksa-enable-p 'quoted-text-only)
4823           (y-or-n-p
4824            "It looks like no new text has been added.  Really post? ")
4825         (message "Denied posting -- no new text has been added.")
4826         nil)))
4827    ;; Check the length of the signature.
4828    (message-check 'signature
4829      (goto-char (point-max))
4830      (if (> (count-lines (point) (point-max)) 5)
4831          (y-or-n-p
4832           (format
4833            "Your .sig is %d lines; it should be max 4.  Really post? "
4834            (1- (count-lines (point) (point-max)))))
4835        t))
4836    ;; Ensure that text follows last quoted portion.
4837    (message-check 'quoting-style
4838      (goto-char (point-max))
4839      (let ((no-problem t))
4840        (when (search-backward-regexp "^>[^\n]*\n" nil t)
4841          (setq no-problem (search-forward-regexp "^[ \t]*[^>\n]" nil t)))
4842        (if no-problem
4843            t
4844          (if (message-gnksa-enable-p 'quoted-text-only)
4845              (y-or-n-p "Your text should follow quoted text.  Really post? ")
4846            ;; Ensure that
4847            (goto-char (point-min))
4848            (re-search-forward
4849             (concat "^" (regexp-quote mail-header-separator) "$"))
4850            (if (search-forward-regexp "^[ \t]*[^>\n]" nil t)
4851                (y-or-n-p "Your text should follow quoted text.  Really post? ")
4852              (message "Denied posting -- only quoted text.")
4853              nil)))))))
4854
4855 (defun message-check-mail-syntax ()
4856   "Check the syntax of the message."
4857   (save-excursion
4858     (save-restriction
4859       (widen)
4860       (and
4861        ;; We narrow to the headers and check them first.
4862        (save-excursion
4863          (save-restriction
4864            (message-narrow-to-headers)
4865            (message-check-mail-header-syntax)))
4866        ;; Check the body.
4867        (save-excursion
4868          (set-buffer message-edit-buffer)
4869          (message-check-mail-body-syntax))))))
4870
4871 (defun message-check-mail-header-syntax ()
4872   t)
4873
4874 (defun message-check-mail-body-syntax ()
4875   (and
4876    ;; Check 8bit characters.
4877    (message-check '8bit
4878      (message-check-8bit)
4879      )))
4880
4881 (defun message-check-8bit ()
4882   "Check the article contains 8bit characters."
4883   (save-excursion
4884     (set-buffer message-encoding-buffer)
4885     (message-narrow-to-headers)
4886     (let* ((case-fold-search t)
4887            (field-value (message-fetch-field "content-transfer-encoding")))
4888       (if (and field-value
4889                (member (downcase field-value) message-8bit-encoding-list))
4890           t
4891         (widen)
4892         (set-buffer (get-buffer-create " message syntax"))
4893         (erase-buffer)
4894         (goto-char (point-min))
4895         (set-buffer-multibyte nil)
4896         (insert-buffer-substring message-encoding-buffer)
4897         (goto-char (point-min))
4898         (if (re-search-forward "[^\x00-\x7f]" nil t)
4899             (y-or-n-p
4900              "The article contains 8bit characters.  Really post? ")
4901           t)))))
4902
4903 (defun message-checksum ()
4904   "Return a \"checksum\" for the current buffer."
4905   (let ((sum 0))
4906     (save-excursion
4907       (goto-char (point-min))
4908       (re-search-forward
4909        (concat "^" (regexp-quote mail-header-separator) "$"))
4910       (while (not (eobp))
4911         (when (not (looking-at "[ \t\n]"))
4912           (setq sum (logxor (ash sum 1) (if (natnump sum) 0 1)
4913                             (char-after))))
4914         (forward-char 1)))
4915     sum))
4916
4917 (defun message-do-fcc ()
4918   "Process Fcc headers in the current buffer."
4919   (let ((case-fold-search t)
4920         (coding-system-for-write 'raw-text)
4921         (output-coding-system 'raw-text)
4922         list file
4923         (mml-externalize-attachments message-fcc-externalize-attachments))
4924     (save-excursion
4925       (save-restriction
4926         (message-narrow-to-headers)
4927         (setq file (message-fetch-field "fcc" t)))
4928       (when file
4929         (set-buffer (get-buffer-create " *message temp*"))
4930         (erase-buffer)
4931         (insert-buffer-substring message-encoding-buffer)
4932         (save-restriction
4933           (message-narrow-to-headers)
4934           (while (setq file (message-fetch-field "fcc"))
4935             (push file list)
4936             (message-remove-header "fcc" nil t)))
4937         (goto-char (point-min))
4938         (when (re-search-forward
4939                (concat "^" (regexp-quote mail-header-separator) "$")
4940                nil t)
4941           (replace-match "" t t))
4942         ;; Process FCC operations.
4943         (while list
4944           (setq file (pop list))
4945           (if (string-match "^[ \t]*|[ \t]*\\(.*\\)[ \t]*$" file)
4946               ;; Pipe the article to the program in question.
4947               (call-process-region (point-min) (point-max) shell-file-name
4948                                    nil nil nil shell-command-switch
4949                                    (match-string 1 file))
4950             ;; Save the article.
4951             (setq file (expand-file-name file))
4952             (unless (file-exists-p (file-name-directory file))
4953               (make-directory (file-name-directory file) t))
4954             (if (and message-fcc-handler-function
4955                      (not (eq message-fcc-handler-function 'rmail-output)))
4956                 (funcall message-fcc-handler-function file)
4957               (if (and (file-readable-p file) (mail-file-babyl-p file))
4958                   (rmail-output file 1 nil t)
4959                 (let ((mail-use-rfc822 t))
4960                   (rmail-output file 1 t t))))))
4961         (kill-buffer (current-buffer))))))
4962
4963 (defun message-output (filename)
4964   "Append this article to Unix/babyl mail file FILENAME."
4965   (if (and (file-readable-p filename)
4966            (mail-file-babyl-p filename))
4967       (gnus-output-to-rmail filename t)
4968     (gnus-output-to-mail filename t)))
4969
4970 (defun message-cleanup-headers ()
4971   "Do various automatic cleanups of the headers."
4972   ;; Remove empty lines in the header.
4973   (save-restriction
4974     (message-narrow-to-headers)
4975     ;; Remove blank lines.
4976     (while (re-search-forward "^[ \t]*\n" nil t)
4977       (replace-match "" t t))
4978
4979     ;; Correct Newsgroups and Followup-To headers:  Change sequence of
4980     ;; spaces to comma and eliminate spaces around commas.  Eliminate
4981     ;; embedded line breaks.
4982     (goto-char (point-min))
4983     (while (re-search-forward "^\\(Newsgroups\\|Followup-To\\): +" nil t)
4984       (save-restriction
4985         (narrow-to-region
4986          (point)
4987          (if (re-search-forward "^[^ \t]" nil t)
4988              (match-beginning 0)
4989            (forward-line 1)
4990            (point)))
4991         (goto-char (point-min))
4992         (while (re-search-forward "\n[ \t]+" nil t)
4993           (replace-match " " t t))      ;No line breaks (too confusing)
4994         (goto-char (point-min))
4995         (while (re-search-forward "[ \t\n]*,[ \t\n]*\\|[ \t]+" nil t)
4996           (replace-match "," t t))
4997         (goto-char (point-min))
4998         ;; Remove trailing commas.
4999         (when (re-search-forward ",+$" nil t)
5000           (replace-match "" t t))))))
5001
5002 (defun message-make-date (&optional now)
5003   "Make a valid data header.
5004 If NOW, use that time instead."
5005   (let* ((now (or now (current-time)))
5006          (zone (nth 8 (decode-time now)))
5007          (sign "+"))
5008     (when (< zone 0)
5009       (setq sign "-")
5010       (setq zone (- zone)))
5011     (concat
5012      ;; The day name of the %a spec is locale-specific.  Pfff.
5013      (format "%s, " (capitalize (car (rassoc (nth 6 (decode-time now))
5014                                              parse-time-weekdays))))
5015      (format-time-string "%d" now)
5016      ;; The month name of the %b spec is locale-specific.  Pfff.
5017      (format " %s "
5018              (capitalize (car (rassoc (nth 4 (decode-time now))
5019                                       parse-time-months))))
5020      (format-time-string "%Y %H:%M:%S " now)
5021      ;; We do all of this because XEmacs doesn't have the %z spec.
5022      (format "%s%02d%02d" sign (/ zone 3600) (/ (% zone 3600) 60)))))
5023
5024 (defun message-make-followup-subject (subject)
5025   "Make a followup Subject."
5026   (cond
5027    ((and (eq message-use-subject-re 'guess)
5028          (string-match message-subject-encoded-re-regexp subject))
5029     subject)
5030    (message-use-subject-re
5031     (concat "Re: " (message-strip-subject-re subject)))
5032    (t subject)))
5033
5034 (defun message-make-message-id ()
5035   "Make a unique Message-ID."
5036   (concat "<" (message-unique-id)
5037           (let ((psubject (save-excursion (message-fetch-field "subject")))
5038                 (psupersedes
5039                  (save-excursion (message-fetch-field "supersedes"))))
5040             (if (or
5041                  (and message-reply-headers
5042                       (mail-header-references message-reply-headers)
5043                       (mail-header-subject message-reply-headers)
5044                       psubject
5045                       (not (string=
5046                             (message-strip-subject-re
5047                              (mail-header-subject message-reply-headers))
5048                             (message-strip-subject-re psubject))))
5049                  (and psupersedes
5050                       (string-match "_-_@" psupersedes)))
5051                 "_-_" ""))
5052           "@" (message-make-fqdn) ">"))
5053
5054 (defvar message-unique-id-char nil)
5055
5056 ;; If you ever change this function, make sure the new version
5057 ;; cannot generate IDs that the old version could.
5058 ;; You might for example insert a "." somewhere (not next to another dot
5059 ;; or string boundary), or modify the "fsf" string.
5060 (defun message-unique-id ()
5061   ;; Don't use microseconds from (current-time), they may be unsupported.
5062   ;; Instead we use this randomly inited counter.
5063   (setq message-unique-id-char
5064         (% (1+ (or message-unique-id-char (logand (random t) (1- (lsh 1 20)))))
5065            ;; (current-time) returns 16-bit ints,
5066            ;; and 2^16*25 just fits into 4 digits i base 36.
5067            (* 25 25)))
5068   (let ((tm (current-time)))
5069     (concat
5070      (if (memq system-type '(ms-dos emx vax-vms))
5071          (let ((user (downcase (user-login-name))))
5072            (while (string-match "[^a-z0-9_]" user)
5073              (aset user (match-beginning 0) ?_))
5074            user)
5075        (message-number-base36 (user-uid) -1))
5076      (message-number-base36 (+ (car tm)
5077                                (lsh (% message-unique-id-char 25) 16)) 4)
5078      (message-number-base36 (+ (nth 1 tm)
5079                                (lsh (/ message-unique-id-char 25) 16)) 4)
5080      ;; Append a given name, because while the generated ID is unique
5081      ;; to this newsreader, other newsreaders might otherwise generate
5082      ;; the same ID via another algorithm.
5083      ".fsf")))
5084
5085 (defun message-number-base36 (num len)
5086   (if (if (< len 0)
5087           (<= num 0)
5088         (= len 0))
5089       ""
5090     (concat (message-number-base36 (/ num 36) (1- len))
5091             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
5092                                   (% num 36))))))
5093
5094 (defun message-make-organization ()
5095   "Make an Organization header."
5096   (let* ((organization
5097           (when message-user-organization
5098             (if (functionp message-user-organization)
5099                 (funcall message-user-organization)
5100               message-user-organization))))
5101     (with-temp-buffer
5102       (set-buffer-multibyte t)
5103       (cond ((stringp organization)
5104              (insert organization))
5105             ((and (eq t organization)
5106                   message-user-organization-file
5107                   (file-exists-p message-user-organization-file))
5108              (insert-file-contents message-user-organization-file)))
5109       (goto-char (point-min))
5110       (while (re-search-forward "[\t\n]+" nil t)
5111         (replace-match "" t t))
5112       (unless (zerop (buffer-size))
5113         (buffer-string)))))
5114
5115 (defun message-make-lines ()
5116   "Count the number of lines and return numeric string."
5117   (save-excursion
5118     (save-restriction
5119       (widen)
5120       (message-goto-body)
5121       (int-to-string (count-lines (point) (point-max))))))
5122
5123 (defun message-make-references ()
5124   "Return the References header for this message."
5125   (when message-reply-headers
5126     (let ((message-id (mail-header-message-id message-reply-headers))
5127           (references (mail-header-references message-reply-headers))
5128           new-references)
5129       (if (or references message-id)
5130           (concat (or references "") (and references " ")
5131                   (or message-id ""))
5132         nil))))
5133
5134 (defun message-make-in-reply-to ()
5135   "Return the In-Reply-To header for this message."
5136   (when message-reply-headers
5137     (let ((from (mail-header-from message-reply-headers))
5138           (date (mail-header-date message-reply-headers))
5139           (msg-id (mail-header-message-id message-reply-headers)))
5140       (when from
5141         (let ((name (std11-extract-address-components from)))
5142           (concat msg-id (if msg-id " (")
5143                   (or (car name)
5144                       (nth 1 name))
5145                   "'s message of \""
5146                   (if (or (not date) (string= date ""))
5147                       "(unknown date)" date)
5148                   "\"" (if msg-id ")")))))))
5149
5150 (defun message-make-distribution ()
5151   "Make a Distribution header."
5152   (let ((orig-distribution (message-fetch-reply-field "distribution")))
5153     (cond ((functionp message-distribution-function)
5154            (funcall message-distribution-function))
5155           (t orig-distribution))))
5156
5157 (defun message-make-expires ()
5158   "Return an Expires header based on `message-expires'."
5159   (let ((current (current-time))
5160         (future (* 1.0 message-expires 60 60 24)))
5161     ;; Add the future to current.
5162     (setcar current (+ (car current) (round (/ future (expt 2 16)))))
5163     (setcar (cdr current) (+ (nth 1 current) (% (round future) (expt 2 16))))
5164     (message-make-date current)))
5165
5166 (defun message-make-path ()
5167   "Return uucp path."
5168   (let ((login-name (user-login-name)))
5169     (cond ((null message-user-path)
5170            (concat (system-name) "!" login-name))
5171           ((stringp message-user-path)
5172            ;; Support GENERICPATH.  Suggested by vixie@decwrl.dec.com.
5173            (concat message-user-path "!" login-name))
5174           (t login-name))))
5175
5176 (defun message-make-from ()
5177   "Make a From header."
5178   (let* ((style message-from-style)
5179          (login (message-make-address))
5180          (fullname
5181           (or (and (boundp 'user-full-name)
5182                    user-full-name)
5183               (user-full-name))))
5184     (when (string= fullname "&")
5185       (setq fullname (user-login-name)))
5186     (with-temp-buffer
5187       (set-buffer-multibyte t)
5188       (cond
5189        ((or (null style)
5190             (equal fullname ""))
5191         (insert login))
5192        ((or (eq style 'angles)
5193             (and (not (eq style 'parens))
5194                  ;; Use angles if no quoting is needed, or if parens would
5195                  ;; need quoting too.
5196                  (or (not (string-match "[^- !#-'*+/-9=?A-Z^-~]" fullname))
5197                      (let ((tmp (concat fullname nil)))
5198                        (while (string-match "([^()]*)" tmp)
5199                          (aset tmp (match-beginning 0) ?-)
5200                          (aset tmp (1- (match-end 0)) ?-))
5201                        (string-match "[\\()]" tmp)))))
5202         (insert fullname)
5203         (goto-char (point-min))
5204         ;; Look for a character that cannot appear unquoted
5205         ;; according to RFC 822.
5206         (when (re-search-forward "[^- !#-'*+/-9=?A-Z^-~]" nil 1)
5207           ;; Quote fullname, escaping specials.
5208           (goto-char (point-min))
5209           (insert "\"")
5210           (while (re-search-forward "[\"\\]" nil 1)
5211             (replace-match "\\\\\\&" t))
5212           (insert "\""))
5213         (insert " <" login ">"))
5214        (t                               ; 'parens or default
5215         (insert login " (")
5216         (let ((fullname-start (point)))
5217           (insert fullname)
5218           (goto-char fullname-start)
5219           ;; RFC 822 says \ and nonmatching parentheses
5220           ;; must be escaped in comments.
5221           ;; Escape every instance of ()\ ...
5222           (while (re-search-forward "[()\\]" nil 1)
5223             (replace-match "\\\\\\&" t))
5224           ;; ... then undo escaping of matching parentheses,
5225           ;; including matching nested parentheses.
5226           (goto-char fullname-start)
5227           (while (re-search-forward
5228                   "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
5229                   nil 1)
5230             (replace-match "\\1(\\3)" t)
5231             (goto-char fullname-start)))
5232         (insert ")")))
5233       (buffer-string))))
5234
5235 (defun message-make-sender ()
5236   "Return the \"real\" user address.
5237 This function tries to ignore all user modifications, and
5238 give as trustworthy answer as possible."
5239   (concat (user-login-name) "@" (system-name)))
5240
5241 (defun message-make-address ()
5242   "Make the address of the user."
5243   (or (message-user-mail-address)
5244       (concat (user-login-name) "@" (message-make-domain))))
5245
5246 (defun message-user-mail-address ()
5247   "Return the pertinent part of `user-mail-address'."
5248   (when (and user-mail-address
5249              (string-match "@.*\\." user-mail-address))
5250     (if (string-match " " user-mail-address)
5251         (nth 1 (std11-extract-address-components user-mail-address))
5252       user-mail-address)))
5253
5254 (defun message-sendmail-envelope-from ()
5255   "Return the envelope from."
5256   (cond ((eq message-sendmail-envelope-from 'header)
5257          (nth 1 (std11-extract-address-components
5258                  (message-fetch-field "from"))))
5259         ((stringp message-sendmail-envelope-from)
5260          message-sendmail-envelope-from)
5261         (t
5262          (message-make-address))))
5263
5264 (defun message-make-fqdn ()
5265   "Return user's fully qualified domain name."
5266   (let* ((system-name (system-name))
5267          (user-mail (message-user-mail-address))
5268          (user-domain
5269           (if (and user-mail
5270                    (string-match "@\\(.*\\)\\'" user-mail))
5271               (match-string 1 user-mail)))
5272          (case-fold-search t))
5273     (cond
5274      ((and message-user-fqdn
5275            (stringp message-user-fqdn)
5276            (string-match message-valid-fqdn-regexp message-user-fqdn)
5277            (not (string-match message-bogus-system-names message-user-fqdn)))
5278       message-user-fqdn)
5279      ;; `message-user-fqdn' seems to be valid
5280      ((and (string-match message-valid-fqdn-regexp system-name)
5281            (not (string-match message-bogus-system-names system-name)))
5282       ;; `system-name' returned the right result.
5283       system-name)
5284      ;; Try `mail-host-address'.
5285      ((and (boundp 'mail-host-address)
5286            (stringp mail-host-address)
5287            (string-match message-valid-fqdn-regexp mail-host-address)
5288            (not (string-match message-bogus-system-names mail-host-address)))
5289       mail-host-address)
5290      ;; We try `user-mail-address' as a backup.
5291      ((and user-domain
5292            (stringp user-domain)
5293            (string-match message-valid-fqdn-regexp user-domain)
5294            (not (string-match message-bogus-system-names user-domain)))
5295       user-domain)
5296      ;; Default to this bogus thing.
5297      (t
5298       (concat system-name
5299               ".i-did-not-set--mail-host-address--so-tickle-me")))))
5300
5301 (defun message-make-host-name ()
5302   "Return the name of the host."
5303   (let ((fqdn (message-make-fqdn)))
5304     (string-match "^[^.]+\\." fqdn)
5305     (substring fqdn 0 (1- (match-end 0)))))
5306
5307 (defun message-make-domain ()
5308   "Return the domain name."
5309   (or mail-host-address
5310       (message-make-fqdn)))
5311
5312 (defun message-to-list-only ()
5313   "Send a message to the list only.
5314 Remove all addresses but the list address from To and Cc headers."
5315   (interactive)
5316   (let ((listaddr (message-make-mail-followup-to t)))
5317     (when listaddr
5318       (save-excursion
5319         (message-remove-header "to")
5320         (message-remove-header "cc")
5321         (message-position-on-field "To" "X-Draft-From")
5322         (insert listaddr)))))
5323
5324 (defun message-make-mail-followup-to (&optional only-show-subscribed)
5325   "Return the Mail-Followup-To header.
5326 If passed the optional argument ONLY-SHOW-SUBSCRIBED only return the
5327 subscribed address (and not the additional To and Cc header contents)."
5328   (let* ((case-fold-search t)
5329          (to (message-fetch-field "To"))
5330          (cc (message-fetch-field "cc"))
5331          (msg-recipients (concat to (and to cc ", ") cc))
5332          (recipients
5333           (mapcar 'mail-strip-quoted-names
5334                   (message-tokenize-header msg-recipients)))
5335          (file-regexps
5336           (if message-subscribed-address-file
5337               (let (begin end item re)
5338                 (save-excursion
5339                   (with-temp-buffer
5340                     (insert-file-contents message-subscribed-address-file)
5341                     (while (not (eobp))
5342                       (setq begin (point))
5343                       (forward-line 1)
5344                       (setq end (point))
5345                       (if (bolp) (setq end (1- end)))
5346                       (setq item (regexp-quote (buffer-substring begin end)))
5347                       (if re (setq re (concat re "\\|" item))
5348                         (setq re (concat "\\`\\(" item))))
5349                     (and re (list (concat re "\\)\\'"))))))))
5350          (mft-regexps (apply 'append message-subscribed-regexps
5351                              (mapcar 'regexp-quote
5352                                      message-subscribed-addresses)
5353                              file-regexps
5354                              (mapcar 'funcall
5355                                      message-subscribed-address-functions))))
5356     (save-match-data
5357       (let ((subscribed-lists nil)
5358             (list
5359              (loop for recipient in recipients
5360                when (loop for regexp in mft-regexps
5361                       when (string-match regexp recipient) return t)
5362                return recipient)))
5363         (when list
5364           (if only-show-subscribed
5365               list
5366             msg-recipients))))))
5367
5368 ;; Dummy to avoid byte-compile warning.
5369 (defvar mule-version)
5370 (defvar emacs-beta-version)
5371 (defvar xemacs-codename)
5372 (defvar gnus-inviolable-extended-version)
5373
5374 (defun message-make-user-agent ()
5375   "Return user-agent info if the value `message-user-agent' is non-nil. If the
5376 \"User-Agent\" field has already exist, remove it."
5377   (when message-user-agent
5378     (save-excursion
5379       (goto-char (point-min))
5380       (let ((case-fold-search t))
5381         (when (re-search-forward "^User-Agent:[\t ]*" nil t)
5382           (delete-region (match-beginning 0) (1+ (std11-field-end)))))))
5383   message-user-agent)
5384
5385 (defun message-idna-inside-rhs-p ()
5386   "Return t iff point is inside a RHS (heuristically).
5387 Only works properly if header contains mailbox-list or address-list.
5388 I.e., calling it on a Subject: header is useless."
5389   (save-restriction
5390     (narrow-to-region (save-excursion (or (re-search-backward "^[^ \t]" nil t)
5391                                           (point-min)))
5392                       (save-excursion (or (re-search-forward "^[^ \t]" nil t)
5393                                           (point-max))))
5394     (if (re-search-backward "[\\\n\r\t ]"
5395                             (save-excursion (search-backward "@" nil t)) t)
5396         ;; whitespace between @ and point
5397         nil
5398       (let ((dquote 1) (paren 1))
5399         (while (save-excursion (re-search-backward "[^\\]\"" nil t dquote))
5400           (incf dquote))
5401         (while (save-excursion (re-search-backward "[^\\]\(" nil t paren))
5402           (incf paren))
5403         (and (= (% dquote 2) 1) (= (% paren 2) 1))))))
5404
5405 (autoload 'idna-to-ascii "idna")
5406
5407 (defun message-idna-to-ascii-rhs-1 (header)
5408   "Interactively potentially IDNA encode domain names in HEADER."
5409   (let (rhs ace start startpos endpos ovl)
5410     (goto-char (point-min))
5411     (while (re-search-forward (concat "^" header) nil t)
5412       (while (re-search-forward "@\\([^ \t\r\n>,]+\\)"
5413                                 (or (save-excursion
5414                                       (re-search-forward "^[^ \t]" nil t))
5415                                     (point-max))
5416                                 t)
5417         (setq rhs (match-string-no-properties 1)
5418               startpos (match-beginning 1)
5419               endpos (match-end 1))
5420         (when (save-match-data
5421                 (and (message-idna-inside-rhs-p)
5422                      (setq ace (idna-to-ascii rhs))
5423                      (not (string= rhs ace))
5424                      (if (eq message-use-idna 'ask)
5425                          (unwind-protect
5426                              (progn
5427                                (setq ovl (message-make-overlay startpos
5428                                                                endpos))
5429                                (message-overlay-put ovl 'face 'highlight)
5430                                (y-or-n-p
5431                                 (format "Replace with `%s'? " ace)))
5432                            (message "")
5433                            (message-delete-overlay ovl))
5434                        message-use-idna)))
5435           (replace-match (concat "@" ace)))))))
5436
5437 (defun message-idna-to-ascii-rhs ()
5438   "Possibly IDNA encode non-ASCII domain names in From:, To: and Cc: headers.
5439 See `message-idna-encode'."
5440   (interactive)
5441   (when message-use-idna
5442     (save-excursion
5443       (save-restriction
5444         (message-narrow-to-head)
5445         (message-idna-to-ascii-rhs-1 "From")
5446         (message-idna-to-ascii-rhs-1 "To")
5447         (message-idna-to-ascii-rhs-1 "Cc")))))
5448
5449 (defun message-generate-headers (headers)
5450   "Prepare article HEADERS.
5451 Headers already prepared in the buffer are not modified."
5452   (setq headers (append headers message-required-headers))
5453   (save-restriction
5454     (message-narrow-to-headers)
5455     (let* ((Date (message-make-date))
5456            (Message-ID (message-make-message-id))
5457            (Organization (message-make-organization))
5458            (From (message-make-from))
5459            (Path (message-make-path))
5460            (Subject nil)
5461            (Newsgroups nil)
5462            (In-Reply-To (message-make-in-reply-to))
5463            (References (message-make-references))
5464            (To nil)
5465            (Distribution (message-make-distribution))
5466            (Lines (message-make-lines))
5467            (User-Agent (message-make-user-agent))
5468            (Expires (message-make-expires))
5469            (case-fold-search t)
5470            (optionalp nil)
5471            header value elem header-string)
5472       ;; First we remove any old generated headers.
5473       (let ((headers message-deletable-headers))
5474         (unless (buffer-modified-p)
5475           (setq headers (delq 'Message-ID (copy-sequence headers))))
5476         (while headers
5477           (goto-char (point-min))
5478           (and (re-search-forward
5479                 (concat "^" (symbol-name (car headers)) ": *") nil t)
5480                (get-text-property (1+ (match-beginning 0)) 'message-deletable)
5481                (message-delete-line))
5482           (pop headers)))
5483       ;; Go through all the required headers and see if they are in the
5484       ;; articles already.  If they are not, or are empty, they are
5485       ;; inserted automatically - except for Subject, Newsgroups and
5486       ;; Distribution.
5487       (while headers
5488         (goto-char (point-min))
5489         (setq elem (pop headers))
5490         (if (consp elem)
5491             (if (eq (car elem) 'optional)
5492                 (setq header (cdr elem)
5493                       optionalp t)
5494               (setq header (car elem)))
5495           (setq header elem))
5496         (setq header-string  (if (stringp header)
5497                                  header
5498                                (symbol-name header)))
5499         (when (or (not (re-search-forward
5500                         (concat "^"
5501                                 (regexp-quote (downcase header-string))
5502                                 ":")
5503                         nil t))
5504                   (progn
5505                     ;; The header was found.  We insert a space after the
5506                     ;; colon, if there is none.
5507                     (if (/= (char-after) ? ) (insert " ") (forward-char 1))
5508                     ;; Find out whether the header is empty.
5509                     (looking-at "[ \t]*\n[^ \t]")))
5510           ;; So we find out what value we should insert.
5511           (setq value
5512                 (cond
5513                  ((and (consp elem)
5514                        (eq (car elem) 'optional)
5515                        (not (member header-string message-inserted-headers)))
5516                   ;; This is an optional header.  If the cdr of this
5517                   ;; is something that is nil, then we do not insert
5518                   ;; this header.
5519                   (setq header (cdr elem))
5520                   (or (and (functionp (cdr elem))
5521                            (funcall (cdr elem)))
5522                       (and (boundp (cdr elem))
5523                            (symbol-value (cdr elem)))))
5524                  ((consp elem)
5525                   ;; The element is a cons.  Either the cdr is a
5526                   ;; string to be inserted verbatim, or it is a
5527                   ;; function, and we insert the value returned from
5528                   ;; this function.
5529                   (or (and (stringp (cdr elem))
5530                            (cdr elem))
5531                       (and (functionp (cdr elem))
5532                            (funcall (cdr elem)))))
5533                  ((and (boundp header)
5534                        (symbol-value header))
5535                   ;; The element is a symbol.  We insert the value
5536                   ;; of this symbol, if any.
5537                   (symbol-value header))
5538                  ((not (message-check-element header))
5539                   ;; We couldn't generate a value for this header,
5540                   ;; so we just ask the user.
5541                   (read-from-minibuffer
5542                    (format "Empty header for %s; enter value: " header)))))
5543           ;; Finally insert the header.
5544           (when (and value
5545                      (not (equal value "")))
5546             (save-excursion
5547               (if (bolp)
5548                   (progn
5549                     ;; This header didn't exist, so we insert it.
5550                     (goto-char (point-max))
5551                     (let ((formatter
5552                            (cdr (assq header message-header-format-alist))))
5553                       (if formatter
5554                           (funcall formatter header value)
5555                         (insert header-string ": " value))
5556                       ;; We check whether the value was ended by a
5557                       ;; newline.  If now, we insert one.
5558                       (unless (bolp)
5559                         (insert "\n"))
5560                       (forward-line -1)))
5561                 ;; The value of this header was empty, so we clear
5562                 ;; totally and insert the new value.
5563                 (delete-region (point) (gnus-point-at-eol))
5564                 ;; If the header is optional, and the header was
5565                 ;; empty, we can't insert it anyway.
5566                 (unless optionalp
5567                   (push header-string message-inserted-headers)
5568                   (insert value)
5569                   (when (bolp)
5570                     (delete-char -1))))
5571               ;; Add the deletable property to the headers that require it.
5572               (and (memq header message-deletable-headers)
5573                    (progn (beginning-of-line) (looking-at "[^:]+: "))
5574                    (add-text-properties
5575                     (point) (match-end 0)
5576                     '(message-deletable t face italic) (current-buffer)))))))
5577       ;; Insert new Sender if the From is strange.
5578       (let ((from (message-fetch-field "from"))
5579             (sender (message-fetch-field "sender"))
5580             (secure-sender (message-make-sender)))
5581         (when (and from
5582                    (not (message-check-element 'sender))
5583                    (not (string=
5584                          (downcase
5585                           (cadr (std11-extract-address-components from)))
5586                          (downcase secure-sender)))
5587                    (or (null sender)
5588                        (not
5589                         (string=
5590                          (downcase
5591                           (cadr (std11-extract-address-components sender)))
5592                          (downcase secure-sender)))))
5593           (goto-char (point-min))
5594           ;; Rename any old Sender headers to Original-Sender.
5595           (when (re-search-forward "^\\(Original-\\)*Sender:" nil t)
5596             (beginning-of-line)
5597             (insert "Original-")
5598             (beginning-of-line))
5599           (when (or (message-news-p)
5600                     (string-match "@.+\\.." secure-sender))
5601             (insert "Sender: " secure-sender "\n"))))
5602       ;; Check for IDNA
5603       (message-idna-to-ascii-rhs))))
5604
5605 (defun message-insert-courtesy-copy ()
5606   "Insert a courtesy message in mail copies of combined messages."
5607   (let (newsgroups)
5608     (save-excursion
5609       (save-restriction
5610         (message-narrow-to-headers)
5611         (when (setq newsgroups (message-fetch-field "newsgroups"))
5612           (goto-char (point-max))
5613           (insert "Posted-To: " newsgroups "\n")))
5614       (forward-line 1)
5615       (when message-courtesy-message
5616         (cond
5617          ((string-match "%s" message-courtesy-message)
5618           (insert (format message-courtesy-message newsgroups)))
5619          (t
5620           (insert message-courtesy-message)))))))
5621
5622 ;;;
5623 ;;; Setting up a message buffer
5624 ;;;
5625
5626 (defun message-fill-address (header value)
5627   (save-restriction
5628     (narrow-to-region (point) (point))
5629     (insert (capitalize (symbol-name header))
5630             ": "
5631             (if (consp value) (car value) value)
5632             "\n")
5633     (narrow-to-region (point-min) (1- (point-max)))
5634     (let (quoted last)
5635       (goto-char (point-min))
5636       (while (not (eobp))
5637         (skip-chars-forward "^,\"" (point-max))
5638         (if (or (eq (char-after) ?,)
5639                 (eobp))
5640             (when (not quoted)
5641               (if (and (> (current-column) 78)
5642                        last)
5643                   (save-excursion
5644                     (goto-char last)
5645                     (looking-at "[ \t]*")
5646                     (replace-match "\n " t t)))
5647               (setq last (1+ (point))))
5648           (setq quoted (not quoted)))
5649         (unless (eobp)
5650           (forward-char 1))))
5651     (goto-char (point-max))
5652     (widen)
5653     (forward-line 1)))
5654
5655 (defun message-fill-references (header value)
5656   (insert (capitalize (symbol-name header))
5657           ": "
5658           (std11-fill-msg-id-list-string
5659            (if (consp value) (car value) value))
5660           "\n"))
5661
5662 (defun message-split-line ()
5663   "Split current line, moving portion beyond point vertically down.
5664 If the current line has `message-yank-prefix', insert it on the new line."
5665   (interactive "*")
5666   (condition-case nil
5667       (split-line message-yank-prefix) ;; Emacs 21.3.50+ supports arg.
5668     (error
5669      (split-line))))
5670      
5671
5672 (defun message-fill-header (header value)
5673   (let ((begin (point))
5674         (fill-column 78)
5675         (fill-prefix " "))
5676     (insert (capitalize (symbol-name header))
5677             ": "
5678             (if (consp value) (car value) value)
5679             "\n")
5680     (save-restriction
5681       (narrow-to-region begin (point))
5682       (fill-region-as-paragraph begin (point))
5683       ;; Tapdance around looong Message-IDs.
5684       (forward-line -1)
5685       (when (looking-at "[ \t]*$")
5686         (message-delete-line))
5687       (goto-char begin)
5688       (re-search-forward ":" nil t)
5689       (when (looking-at "\n[ \t]+")
5690         (replace-match " " t t))
5691       (goto-char (point-max)))))
5692
5693 (defun message-shorten-1 (list cut surplus)
5694   "Cut SURPLUS elements out of LIST, beginning with CUTth one."
5695   (setcdr (nthcdr (- cut 2) list)
5696           (nthcdr (+ (- cut 2) surplus 1) list)))
5697
5698 (defun message-shorten-references (header references)
5699   "Trim REFERENCES to be 21 Message-ID long or less, and fold them.
5700 If folding is disallowed, also check that the REFERENCES are less
5701 than 988 characters long, and if they are not, trim them until they are."
5702   (let ((maxcount 21)
5703         (count 0)
5704         (cut 2)
5705         refs)
5706     (with-temp-buffer
5707       (insert references)
5708       (goto-char (point-min))
5709       ;; Cons a list of valid references.
5710       (while (re-search-forward "<[^>]+>" nil t)
5711         (push (match-string 0) refs))
5712       (setq refs (nreverse refs)
5713             count (length refs)))
5714
5715     ;; If the list has more than MAXCOUNT elements, trim it by
5716     ;; removing the CUTth element and the required number of
5717     ;; elements that follow.
5718     (when (> count maxcount)
5719       (let ((surplus (- count maxcount)))
5720         (message-shorten-1 refs cut surplus)
5721         (decf count surplus)))
5722
5723     ;; If folding is disallowed, make sure the total length (including
5724     ;; the spaces between) will be less than MAXSIZE characters.
5725     ;;
5726     ;; Only disallow folding for News messages. At this point the headers
5727     ;; have not been generated, thus we use message-this-is-news directly.
5728     (when (and message-this-is-news message-cater-to-broken-inn)
5729       (let ((maxsize 988)
5730             (totalsize (+ (apply #'+ (mapcar #'length refs))
5731                           (1- count)))
5732             (surplus 0)
5733             (ptr (nthcdr (1- cut) refs)))
5734         ;; Decide how many elements to cut off...
5735         (while (> totalsize maxsize)
5736           (decf totalsize (1+ (length (car ptr))))
5737           (incf surplus)
5738           (setq ptr (cdr ptr)))
5739         ;; ...and do it.
5740         (when (> surplus 0)
5741           (message-shorten-1 refs cut surplus))))
5742
5743     ;; Finally, collect the references back into a string and insert
5744     ;; it into the buffer.
5745     (let ((refstring (mapconcat #'identity refs " ")))
5746       (if (and message-this-is-news message-cater-to-broken-inn)
5747           (insert (capitalize (symbol-name header)) ": "
5748                   refstring "\n")
5749         (message-fill-header header refstring)))))
5750
5751 (defun message-position-point ()
5752   "Move point to where the user probably wants to find it."
5753   (message-narrow-to-headers)
5754   (cond
5755    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
5756     (search-backward ":" )
5757     (widen)
5758     (forward-char 1)
5759     (if (eq (char-after) ? )
5760         (forward-char 1)
5761       (insert " ")))
5762    (t
5763     (goto-char (point-max))
5764     (widen)
5765     (forward-line 1)
5766     (unless (looking-at "$")
5767       (forward-line 2)))
5768    (sit-for 0)))
5769
5770 (defcustom message-beginning-of-line t
5771   "Whether \\<message-mode-map>\\[message-beginning-of-line]\
5772  goes to beginning of header values."
5773   :group 'message-buffers
5774   :type 'boolean)
5775
5776 (defun message-beginning-of-line (&optional n)
5777   "Move point to beginning of header value or to beginning of line.
5778 The prefix argument N is passed directly to `beginning-of-line'.
5779
5780 This command is identical to `beginning-of-line' if point is
5781 outside the message header or if the option `message-beginning-of-line'
5782 is nil.
5783
5784 If point is in the message header and on a (non-continued) header
5785 line, move point to the beginning of the header value.  If point
5786 is already there, move point to beginning of line.  Therefore,
5787 repeated calls will toggle point between beginning of field and
5788 beginning of line."
5789   (interactive "p")
5790   (let ((zrs 'zmacs-region-stays))
5791     (when (and (interactive-p) (boundp zrs))
5792       (set zrs t)))
5793   (if (and message-beginning-of-line
5794            (message-point-in-header-p))
5795       (let* ((here (point))
5796              (bol (progn (beginning-of-line n) (point)))
5797              (eol (gnus-point-at-eol))
5798              (eoh (re-search-forward ": *" eol t)))
5799         (if (or (not eoh) (equal here eoh))
5800             (goto-char bol)
5801           (goto-char eoh)))
5802     (beginning-of-line n)))
5803
5804 (defun message-buffer-name (type &optional to group)
5805   "Return a new (unique) buffer name based on TYPE and TO."
5806   (cond
5807    ;; Generate a new buffer name The Message Way.
5808    ((eq message-generate-new-buffers 'unique)
5809     (generate-new-buffer-name
5810      (concat "*" type
5811              (if to
5812                  (concat " to "
5813                          (or (car (std11-extract-address-components to))
5814                              to) "")
5815                "")
5816              (if (and group (not (string= group ""))) (concat " on " group) "")
5817              "*")))
5818    ;; Check whether `message-generate-new-buffers' is a function,
5819    ;; and if so, call it.
5820    ((functionp message-generate-new-buffers)
5821     (funcall message-generate-new-buffers type to group))
5822    ((eq message-generate-new-buffers 'unsent)
5823     (generate-new-buffer-name
5824      (concat "*unsent " type
5825              (if to
5826                  (concat " to "
5827                          (or (car (std11-extract-address-components to))
5828                              to) "")
5829                "")
5830              (if (and group (not (string= group ""))) (concat " on " group) "")
5831              "*")))
5832    ;; Use standard name.
5833    (t
5834     (format "*%s message*" type))))
5835
5836 (defmacro message-pop-to-buffer-1 (buffer)
5837   `(if pop-up-frames
5838        (let (special-display-buffer-names
5839              special-display-regexps
5840              same-window-buffer-names
5841              same-window-regexps)
5842          (pop-to-buffer ,buffer))
5843      (pop-to-buffer ,buffer)))
5844
5845 (defun message-pop-to-buffer (name)
5846   "Pop to buffer NAME, and warn if it already exists and is modified."
5847   (let ((buffer (get-buffer name))
5848         (pop-up-frames (and (or (static-if (featurep 'xemacs)
5849                                     (device-on-window-system-p)
5850                                   window-system)
5851                                 (>= emacs-major-version 20))
5852                             message-use-multi-frames)))
5853     (if (and buffer
5854              (buffer-name buffer))
5855         (progn
5856           (message-pop-to-buffer-1 buffer)
5857           (when (and (buffer-modified-p)
5858                      (not (y-or-n-p
5859                            "Message already being composed; erase? ")))
5860             (error "Message being composed")))
5861       (message-pop-to-buffer-1 name))
5862     (erase-buffer)
5863     (message-mode)
5864     (when pop-up-frames
5865       (set (make-local-variable 'message-original-frame) (selected-frame)))))
5866
5867 (defun message-do-send-housekeeping ()
5868   "Kill old message buffers."
5869   ;; We might have sent this buffer already.  Delete it from the
5870   ;; list of buffers.
5871   (setq message-buffer-list (delq (current-buffer) message-buffer-list))
5872   (while (and message-max-buffers
5873               message-buffer-list
5874               (>= (length message-buffer-list) message-max-buffers))
5875     ;; Kill the oldest buffer -- unless it has been changed.
5876     (let ((buffer (pop message-buffer-list)))
5877       (when (and (buffer-name buffer)
5878                  (not (buffer-modified-p buffer)))
5879         (kill-buffer buffer))))
5880   ;; Rename the buffer.
5881   (if message-send-rename-function
5882       (funcall message-send-rename-function)
5883     ;; Note: mail-abbrevs of XEmacs renames buffer name behind Gnus.
5884     (when (string-match
5885            "\\`\\*\\(sent \\|unsent \\)?\\(.+\\)\\*[^\\*]*\\|\\`mail to "
5886            (buffer-name))
5887       (let ((name (match-string 2 (buffer-name)))
5888             to group)
5889         (if (not (or (null name)
5890                      (string-equal name "mail")
5891                      (string-equal name "posting")))
5892             (setq name (concat "*sent " name "*"))
5893           (message-narrow-to-headers)
5894           (setq to (message-fetch-field "to"))
5895           (setq group (message-fetch-field "newsgroups"))
5896           (widen)
5897           (setq name
5898                 (cond
5899                  (to (concat "*sent mail to "
5900                              (or (car (std11-extract-address-components to))
5901                                  to) "*"))
5902                  ((and group (not (string= group "")))
5903                   (concat "*sent posting on " group "*"))
5904                  (t "*sent mail*"))))
5905         (unless (string-equal name (buffer-name))
5906           (rename-buffer name t)))))
5907   ;; Push the current buffer onto the list.
5908   (when message-max-buffers
5909     (setq message-buffer-list
5910           (nconc message-buffer-list (list (current-buffer))))))
5911
5912 (defun message-mail-user-agent ()
5913   (let ((mua (cond
5914               ((not message-mail-user-agent) nil)
5915               ((eq message-mail-user-agent t) mail-user-agent)
5916               (t message-mail-user-agent))))
5917     (if (memq mua '(message-user-agent gnus-user-agent))
5918         nil
5919       mua)))
5920
5921 (defun message-setup (headers &optional replybuffer actions switch-function)
5922   (let ((mua (message-mail-user-agent))
5923         subject to field yank-action)
5924     (if (not (and message-this-is-mail mua))
5925         (message-setup-1 headers replybuffer actions)
5926       (if replybuffer
5927           (setq yank-action (list 'insert-buffer replybuffer)))
5928       (setq headers (copy-sequence headers))
5929       (setq field (assq 'Subject headers))
5930       (when field
5931         (setq subject (cdr field))
5932         (setq headers (delq field headers)))
5933       (setq field (assq 'To headers))
5934       (when field
5935         (setq to (cdr field))
5936         (setq headers (delq field headers)))
5937       (let ((mail-user-agent mua))
5938         (compose-mail to subject
5939                       (mapcar (lambda (item)
5940                                 (cons
5941                                  (format "%s" (car item))
5942                                  (cdr item)))
5943                               headers)
5944                       nil switch-function yank-action actions)))))
5945
5946 (defun message-headers-to-generate (headers included-headers excluded-headers)
5947   "Return a list that includes all headers from HEADERS.
5948 If INCLUDED-HEADERS is a list, just include those headers.  If if is
5949 t, include all headers.  In any case, headers from EXCLUDED-HEADERS
5950 are not included."
5951   (let ((result nil)
5952         header-name)
5953     (dolist (header headers)
5954       (setq header-name (cond
5955                          ((and (consp header)
5956                                (eq (car header) 'optional))
5957                           ;; On the form (optional . Header)
5958                           (cdr header))
5959                          ((consp header)
5960                           ;; On the form (Header . function)
5961                           (car header))
5962                          (t
5963                           ;; Just a Header.
5964                           header)))
5965       (when (and (not (memq header-name excluded-headers))
5966                  (or (eq included-headers t)
5967                      (memq header-name included-headers)))
5968         (push header result)))
5969     (nreverse result)))
5970
5971 (defun message-setup-1 (headers &optional replybuffer actions)
5972   (dolist (action actions)
5973     (condition-case nil
5974         (add-to-list 'message-send-actions
5975                      `(apply ',(car action) ',(cdr action)))))
5976   (setq message-reply-buffer
5977         (or (message-get-parameter 'reply-buffer)
5978             replybuffer))
5979   (goto-char (point-min))
5980   ;; Insert all the headers.
5981   (mail-header-format
5982    (let ((h headers)
5983          (alist message-header-format-alist))
5984      (while h
5985        (unless (assq (caar h) message-header-format-alist)
5986          (push (list (caar h)) alist))
5987        (pop h))
5988      alist)
5989    headers)
5990   (delete-region (point) (progn (forward-line -1) (point)))
5991   (when message-default-headers
5992     (insert message-default-headers)
5993     (or (bolp) (insert ?\n)))
5994   (put-text-property
5995    (point)
5996    (progn
5997      (insert mail-header-separator "\n")
5998      (1- (point)))
5999    'read-only nil)
6000   (forward-line -1)
6001   (when (message-news-p)
6002     (when message-default-news-headers
6003       (insert message-default-news-headers)
6004       (or (bolp) (insert ?\n)))
6005     (when message-generate-headers-first
6006       (message-generate-headers
6007        (message-headers-to-generate
6008         (append message-required-news-headers
6009                 message-required-headers)
6010         message-generate-headers-first
6011         '(Lines Subject)))))
6012   (when (message-mail-p)
6013     (when message-default-mail-headers
6014       (insert message-default-mail-headers)
6015       (or (bolp) (insert ?\n)))
6016     (save-restriction
6017       (message-narrow-to-headers)
6018       (if (and replybuffer
6019                message-alternative-emails)
6020           (message-use-alternative-email-as-from)))
6021     (when message-generate-headers-first
6022       (message-generate-headers
6023        (message-headers-to-generate
6024         (append message-required-mail-headers
6025                 message-required-headers)
6026         message-generate-headers-first
6027         '(Lines Subject)))))
6028   (run-hooks 'message-signature-setup-hook)
6029   (message-insert-signature)
6030   (save-restriction
6031     (message-narrow-to-headers)
6032     (run-hooks 'message-header-setup-hook))
6033   (set-buffer-modified-p nil)
6034   (setq buffer-undo-list nil)
6035   (run-hooks 'message-setup-hook)
6036   (message-position-point)
6037   (undo-boundary))
6038
6039 (defun message-set-auto-save-file-name ()
6040   "Associate the message buffer with a file in the drafts directory."
6041   (when message-auto-save-directory
6042     (unless (file-directory-p
6043              (directory-file-name message-auto-save-directory))
6044       (make-directory message-auto-save-directory t))
6045     (if (gnus-alive-p)
6046         (setq message-draft-article
6047               (nndraft-request-associate-buffer "drafts"))
6048       (setq buffer-file-name (expand-file-name
6049                               (if (memq system-type
6050                                         '(ms-dos ms-windows windows-nt
6051                                                  cygwin cygwin32 win32 w32
6052                                                  mswindows))
6053                                   "message"
6054                                 "*message*")
6055                               message-auto-save-directory))
6056       (setq buffer-auto-save-file-name (make-auto-save-file-name)))
6057     (clear-visited-file-modtime)
6058     (static-if (boundp 'MULE)
6059         (set-file-coding-system message-draft-coding-system)
6060       (setq buffer-file-coding-system message-draft-coding-system))))
6061
6062 (defun message-disassociate-draft ()
6063   "Disassociate the message buffer from the drafts directory."
6064   (when message-draft-article
6065     (nndraft-request-expire-articles
6066      (list message-draft-article) "drafts" nil t)))
6067
6068 (defun message-insert-headers ()
6069   "Generate the headers for the article."
6070   (interactive)
6071   (save-excursion
6072     (save-restriction
6073       (message-narrow-to-headers)
6074       (when (message-news-p)
6075         (message-generate-headers
6076          (delq 'Lines
6077                (delq 'Subject
6078                      (copy-sequence message-required-news-headers)))))
6079       (when (message-mail-p)
6080         (message-generate-headers
6081          (delq 'Lines
6082                (delq 'Subject
6083                      (copy-sequence message-required-mail-headers))))))))
6084
6085 \f
6086
6087 ;;;
6088 ;;; Commands for interfacing with message
6089 ;;;
6090
6091 ;;;###autoload
6092 (defun message-mail (&optional to subject
6093                                other-headers continue switch-function
6094                                yank-action send-actions)
6095   "Start editing a mail message to be sent.
6096 OTHER-HEADERS is an alist of header/value pairs."
6097   (interactive)
6098   (let ((message-this-is-mail t) replybuffer)
6099     (unless (message-mail-user-agent)
6100       (message-pop-to-buffer (message-buffer-name "mail" to)))
6101     ;; FIXME: message-mail should do something if YANK-ACTION is not
6102     ;; insert-buffer.
6103     (and (consp yank-action) (eq (car yank-action) 'insert-buffer)
6104          (setq replybuffer (nth 1 yank-action)))
6105     (message-setup
6106      (nconc
6107       `((To . ,(or to "")) (Subject . ,(or subject "")))
6108       (when other-headers other-headers))
6109      replybuffer send-actions)
6110     ;; FIXME: Should return nil if failure.
6111     t))
6112
6113 ;;;###autoload
6114 (defun message-news (&optional newsgroups subject)
6115   "Start editing a news article to be sent."
6116   (interactive)
6117   (let ((message-this-is-news t))
6118     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups))
6119     (message-setup `((Newsgroups . ,(or newsgroups ""))
6120                      (Subject . ,(or subject ""))))))
6121
6122 (defun message-get-reply-headers (wide &optional to-address address-headers)
6123   (let (follow-to mct never-mct to cc author mft recipients)
6124     ;; Find all relevant headers we need.
6125     (let ((mrt (when message-use-mail-reply-to
6126                  (message-fetch-field "mail-reply-to")))
6127           (reply-to (message-fetch-field "reply-to")))
6128       (setq to (message-fetch-field "to")
6129             cc (message-fetch-field "cc")
6130             mct (when message-use-mail-copies-to
6131                   (message-fetch-field "mail-copies-to"))
6132             author (or mrt
6133                        reply-to
6134                        (message-fetch-field "from")
6135                        "")
6136             mft (when (and (not (or to-address mrt reply-to))
6137                            message-use-mail-followup-to)
6138                   (message-fetch-field "mail-followup-to"))))
6139
6140     (save-match-data
6141       ;; Handle special values of Mail-Copies-To.
6142       (when mct
6143         (cond ((or (equal (downcase mct) "never")
6144                    (equal (downcase mct) "nobody"))
6145                (when (or (not (eq message-use-mail-copies-to 'ask))
6146                          (message-y-or-n-p
6147                           (concat "Obey Mail-Copies-To: never? ") t "\
6148 You should normally obey the Mail-Copies-To: header.
6149
6150         `Mail-Copies-To: " mct "'
6151 directs you not to send your response to the author."))
6152                  (setq never-mct t))
6153                (setq mct nil))
6154               ((or (equal (downcase mct) "always")
6155                    (equal (downcase mct) "poster"))
6156                (if (or (not (eq message-use-mail-copies-to 'ask))
6157                        (message-y-or-n-p
6158                         (concat "Obey Mail-Copies-To: always? ") t "\
6159 You should normally obey the Mail-Copies-To: header.
6160
6161         `Mail-Copies-To: " mct "'
6162 sends a copy of your response to the author."))
6163                    (setq mct author)
6164                  (setq mct nil)))
6165               ((and (eq message-use-mail-copies-to 'ask)
6166                     (not (message-y-or-n-p
6167                           (concat "Obey Mail-Copies-To: " mct " ? ") t "\
6168 You should normally obey the Mail-Copies-To: header.
6169
6170         `Mail-Copies-To: " mct "'
6171 sends a copy of your response to " (if (string-match "," mct)
6172                                        "the specified addresses"
6173                                      "that address") ".")))
6174                (setq mct nil))))
6175
6176       ;; Build (textual) list of new recipient addresses.
6177       (cond
6178        ((not wide)
6179         (setq recipients (concat ", " author)))
6180        (address-headers
6181         (dolist (header address-headers)
6182           (let ((value (message-fetch-field header)))
6183             (when value
6184               (setq recipients (concat recipients ", " value))))))
6185        ((and mft
6186              (string-match "[^ \t,]" mft)
6187              (or (not (eq message-use-mail-followup-to 'ask))
6188                  (message-y-or-n-p "Obey Mail-Followup-To? " t "\
6189 You should normally obey the Mail-Followup-To: header.  In this
6190 article, it has the value of
6191
6192 " mft "
6193
6194 which directs your response to " (if (string-match "," mft)
6195                                      "the specified addresses"
6196                                    "that address only") ".
6197
6198 Most commonly, Mail-Followup-To is used by a mailing list poster to
6199 express that responses should be sent to just the list, and not the
6200 poster as well.
6201
6202 If a message is posted to several mailing lists, Mail-Followup-To may
6203 also be used to direct the following discussion to one list only,
6204 because discussions that are spread over several lists tend to be
6205 fragmented and very difficult to follow.
6206
6207 Also, some source/announcement lists are not intended for discussion;
6208 responses here are directed to other addresses.")))
6209         (setq recipients (concat ", " mft)))
6210        (to-address
6211         (setq recipients (concat ", " to-address))
6212         ;; If the author explicitly asked for a copy, we don't deny it to them.
6213         (if mct (setq recipients (concat recipients ", " mct))))
6214        (t
6215         (setq recipients (if never-mct "" (concat ", " author)))
6216         (if to  (setq recipients (concat recipients ", " to)))
6217         (if cc  (setq recipients (concat recipients ", " cc)))
6218         (if mct (setq recipients (concat recipients ", " mct)))))
6219       (if (>= (length recipients) 2)
6220           ;; Strip the leading ", ".
6221           (setq recipients (substring recipients 2)))
6222       ;; Squeeze whitespace.
6223       (while (string-match "[ \t][ \t]+" recipients)
6224         (setq recipients (replace-match " " t t recipients)))
6225       ;; Remove addresses that match `rmail-dont-reply-to-names'.
6226       (let ((rmail-dont-reply-to-names message-dont-reply-to-names))
6227         (setq recipients (rmail-dont-reply-to recipients)))
6228       ;; Perhaps "Mail-Copies-To: never" removed the only address?
6229       (if (string-equal recipients "")
6230           (setq recipients author))
6231       ;; Convert string to a list of (("foo@bar" . "Name <Foo@BAR>") ...).
6232       (setq recipients
6233             (mapcar
6234              (lambda (addr)
6235                (cons (downcase (mail-strip-quoted-names addr)) addr))
6236              (message-tokenize-header recipients)))
6237       ;; Remove first duplicates.  (Why not all duplicates?  Is this a bug?)
6238       (let ((s recipients))
6239         (while s
6240           (setq recipients (delq (assoc (car (pop s)) s) recipients))))
6241
6242       ;; Remove hierarchical lists that are contained within each other,
6243       ;; if message-hierarchical-addresses is defined.
6244       (when message-hierarchical-addresses
6245         (let ((plain-addrs (mapcar 'car recipients))
6246               subaddrs recip)
6247           (while plain-addrs
6248             (setq subaddrs (assoc (car plain-addrs)
6249                                   message-hierarchical-addresses)
6250                   plain-addrs (cdr plain-addrs))
6251             (when subaddrs
6252               (setq subaddrs (cdr subaddrs))
6253               (while subaddrs
6254                 (setq recip (assoc (car subaddrs) recipients)
6255                       subaddrs (cdr subaddrs))
6256                 (if recip
6257                     (setq recipients (delq recip recipients))))))))
6258
6259       ;; Build the header alist.  Allow the user to be asked whether
6260       ;; or not to reply to all recipients in a wide reply.
6261       (setq follow-to (list (cons 'To (cdr (pop recipients)))))
6262       (when (and recipients
6263                  (or (not message-wide-reply-confirm-recipients)
6264                      (y-or-n-p "Reply to all recipients? ")))
6265         (setq recipients (mapconcat
6266                           (lambda (addr) (cdr addr)) recipients ", "))
6267         (if (string-match "^ +" recipients)
6268             (setq recipients (substring recipients (match-end 0))))
6269         (push (cons 'Cc recipients) follow-to)))
6270     follow-to))
6271
6272 ;;;###autoload
6273 (defun message-reply (&optional to-address wide)
6274   "Start editing a reply to the article in the current buffer."
6275   (interactive)
6276   (require 'gnus-sum)                   ; for gnus-list-identifiers
6277   (let ((cur (current-buffer))
6278         from subject date
6279         references message-id follow-to
6280         (inhibit-point-motion-hooks t)
6281         (message-this-is-mail t)
6282         gnus-warning in-reply-to)
6283     (save-restriction
6284       (message-narrow-to-head-1)
6285       ;; Allow customizations to have their say.
6286       (if (not wide)
6287           ;; This is a regular reply.
6288           (when (functionp message-reply-to-function)
6289             (save-excursion
6290               (setq follow-to (funcall message-reply-to-function))))
6291         ;; This is a followup.
6292         (when (functionp message-wide-reply-to-function)
6293           (save-excursion
6294             (setq follow-to
6295                   (funcall message-wide-reply-to-function)))))
6296       (setq message-id (message-fetch-field "message-id" t)
6297             references (message-fetch-field "references")
6298             date (message-fetch-field "date")
6299             from (message-fetch-field "from")
6300             subject (or (message-fetch-field "subject") "none"))
6301       (when gnus-list-identifiers
6302         (setq subject (message-strip-list-identifiers subject)))
6303       (setq subject (message-make-followup-subject subject))
6304       (when message-subject-trailing-was-query
6305         (setq subject (message-strip-subject-trailing-was subject)))
6306
6307       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
6308                  (string-match "<[^>]+>" gnus-warning))
6309         (setq message-id (match-string 0 gnus-warning)))
6310
6311       (unless follow-to
6312         (setq follow-to (message-get-reply-headers wide to-address)))
6313
6314       ;; Get the references from "In-Reply-To" field if there were
6315       ;; no references and "In-Reply-To" field looks promising.
6316       (unless references
6317         (when (and (setq in-reply-to (message-fetch-field "in-reply-to"))
6318                    (string-match "<[^>]+>" in-reply-to))
6319           (setq references (match-string 0 in-reply-to)))))
6320
6321     (unless (message-mail-user-agent)
6322       (message-pop-to-buffer
6323        (message-buffer-name
6324         (if wide "wide reply" "reply") from
6325         (if wide to-address nil))))
6326
6327     (setq message-reply-headers
6328           (make-full-mail-header-from-decoded-header
6329            0 subject from date message-id references 0 0 ""))
6330
6331     (message-setup
6332      `((Subject . ,subject)
6333        ,@follow-to)
6334      cur)))
6335
6336 ;;;###autoload
6337 (defun message-wide-reply (&optional to-address)
6338   "Make a \"wide\" reply to the message in the current buffer."
6339   (interactive)
6340   (message-reply to-address t))
6341
6342 ;;;###autoload
6343 (defun message-followup (&optional to-newsgroups)
6344   "Follow up to the message in the current buffer.
6345 If TO-NEWSGROUPS, use that as the new Newsgroups line."
6346   (interactive)
6347   (require 'gnus-sum)                   ; for gnus-list-identifiers
6348   (let ((cur (current-buffer))
6349         from subject date reply-to mrt mct mft
6350         references message-id follow-to
6351         (inhibit-point-motion-hooks t)
6352         (message-this-is-news t)
6353         followup-to distribution newsgroups gnus-warning posted-to)
6354     (save-restriction
6355       (message-narrow-to-head)
6356       (when (functionp message-followup-to-function)
6357         (setq follow-to
6358               (funcall message-followup-to-function)))
6359       (setq from (message-fetch-field "from")
6360             date (message-fetch-field "date")
6361             subject (or (message-fetch-field "subject") "none")
6362             references (message-fetch-field "references")
6363             message-id (message-fetch-field "message-id" t)
6364             followup-to (message-fetch-field "followup-to")
6365             newsgroups (message-fetch-field "newsgroups")
6366             posted-to (message-fetch-field "posted-to")
6367             reply-to (message-fetch-field "reply-to")
6368             mrt (when message-use-mail-reply-to
6369                   (message-fetch-field "mail-reply-to"))
6370             distribution (message-fetch-field "distribution")
6371             mct (when message-use-mail-copies-to
6372                   (message-fetch-field "mail-copies-to"))
6373             mft (when message-use-mail-followup-to
6374                   (message-fetch-field "mail-followup-to")))
6375       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
6376                  (string-match "<[^>]+>" gnus-warning))
6377         (setq message-id (match-string 0 gnus-warning)))
6378       ;; Remove bogus distribution.
6379       (when (and (stringp distribution)
6380                  (let ((case-fold-search t))
6381                    (string-match "world" distribution)))
6382         (setq distribution nil))
6383       (if gnus-list-identifiers
6384           (setq subject (message-strip-list-identifiers subject)))
6385       (setq subject (message-make-followup-subject subject))
6386       (when message-subject-trailing-was-query
6387         (setq subject (message-strip-subject-trailing-was subject)))
6388       (widen))
6389
6390     ;; Handle special values of Mail-Copies-To.
6391     (when mct
6392       (cond
6393        ((and (or (equal (downcase mct) "never")
6394                  (equal (downcase mct) "nobody")))
6395         (setq mct nil))
6396        ((and (or (equal (downcase mct) "always")
6397                  (equal (downcase mct) "poster")))
6398         (if (or (not (eq message-use-mail-copies-to 'ask))
6399                 (message-y-or-n-p
6400                  (concat "Obey Mail-Copies-To: always? ") t "\
6401 You should normally obey the Mail-Copies-To: header.
6402
6403         `Mail-Copies-To: " mct "'
6404 sends a copy of your response to the author."))
6405             (setq mct (or mrt reply-to from))
6406           (setq mct nil)))
6407        ((and (eq message-use-mail-copies-to 'ask)
6408              (not
6409               (message-y-or-n-p
6410                (concat "Obey Mail-Copies-To: " mct " ? ") t "\
6411 You should normally obey the Mail-Copies-To: header.
6412
6413         `Mail-Copies-To: " mct "'
6414 sends a copy of your response to " (if (string-match "," mct)
6415                                        "the specified addresses"
6416                                      "that address") ".")))
6417         (setq mct nil))))
6418
6419     (unless follow-to
6420       (cond
6421        (to-newsgroups (setq follow-to (list (cons 'Newsgroups to-newsgroups))))
6422        ;; Handle Followup-To.
6423        (followup-to
6424         (cond
6425          ((equal (downcase followup-to) "poster")
6426           (if (or (and followup-to (eq message-use-followup-to 'use))
6427                   (message-y-or-n-p "Obey Followup-To: poster? " t "\
6428 You should normally obey the Followup-To: header.
6429
6430         `Followup-To: poster'
6431 sends your response via e-mail instead of news.
6432
6433 A typical situation where `Followup-To: poster' is used is when the author
6434 does not read the newsgroup, so he wouldn't see any replies sent to it."))
6435               (setq message-this-is-news nil
6436                     distribution nil
6437                     follow-to (list (cons 'To (or mrt reply-to from ""))))
6438             (setq follow-to (list (cons 'Newsgroups newsgroups)))))
6439          (t
6440           (if (or (equal followup-to newsgroups)
6441                   (not (and followup-to (eq message-use-followup-to 'ask)))
6442                   (message-y-or-n-p
6443                    (concat "Obey Followup-To: " followup-to "? ") t "\
6444 You should normally obey the Followup-To: header.
6445
6446         `Followup-To: " followup-to "'
6447 directs your response to " (if (string-match "," followup-to)
6448                                "the specified newsgroups"
6449                              "that newsgroup only") ".
6450
6451 If a message is posted to several newsgroups, Followup-To is often
6452 used to direct the following discussion to one newsgroup only,
6453 because discussions that are spread over several newsgroup tend to
6454 be fragmented and very difficult to follow.
6455
6456 Also, some source/announcement newsgroups are not intended for discussion;
6457 responses here are directed to other newsgroups."))
6458               (setq follow-to (list (cons 'Newsgroups followup-to)))
6459             (setq follow-to (list (cons 'Newsgroups newsgroups)))))))
6460        ;; Handle Mail-Followup-To, followup via e-mail.
6461        ((and mft
6462              (or (not (eq message-use-mail-followup-to 'ask))
6463                  (message-y-or-n-p
6464                   (concat "Obey Mail-Followup-To: " mft "? ") t "\
6465 You should normally obey the Mail-Followup-To: header.
6466
6467         `Mail-Followup-To: " mft "'
6468 directs your response to " (if (string-match "," mft)
6469                                "the specified addresses"
6470                              "that address only") " instead of news.
6471
6472 A typical situation where Mail-Followup-To is used is when the author thinks
6473 that further discussion should take place only in "
6474                              (if (string-match "," mft)
6475                                  "the specified mailing lists"
6476                                "that mailing list") ".")))
6477         (setq message-this-is-news nil
6478               distribution nil
6479               follow-to (list (cons 'To mft))))
6480        (posted-to (setq follow-to (list (cons 'Newsgroups posted-to))))
6481        (t
6482         (setq follow-to (list (cons 'Newsgroups newsgroups))))))
6483
6484     (message-pop-to-buffer (message-buffer-name "followup" from newsgroups))
6485
6486     (setq message-reply-headers
6487           (make-full-mail-header-from-decoded-header
6488            0 subject from date message-id references 0 0 ""))
6489
6490     (message-setup
6491      `((Subject . ,subject)
6492        ,@follow-to
6493        ,@(and mct (list (cons 'Cc mct)))
6494        ,@(and distribution (list (cons 'Distribution distribution))))
6495      cur)))
6496
6497 (defun message-is-yours-p ()
6498   "Non-nil means current article is yours.
6499 If you have added 'cancel-messages to 'message-shoot-gnksa-feet', all articles
6500 are yours except those that have Cancel-Lock header not belonging to you.
6501 Instead of shooting GNKSA feet, you should modify 'message-alternative-emails'
6502 regexp to match all of yours addresses."
6503   ;; Canlock-logic as suggested by Per Abrahamsen
6504   ;; <abraham@dina.kvl.dk>
6505   ;;
6506   ;; IF article has cancel-lock THEN
6507   ;;   IF we can verify it THEN
6508   ;;     issue cancel
6509   ;;   ELSE
6510   ;;     error: cancellock: article is not yours
6511   ;; ELSE
6512   ;;   Use old rules, comparing sender...
6513   (save-excursion
6514     (save-restriction
6515       (message-narrow-to-head-1)
6516       (if (message-fetch-field "Cancel-Lock")
6517           (if (null (canlock-verify))
6518               t
6519             (error "Failed to verify Cancel-lock: This article is not yours"))
6520         (let (sender from)
6521           (or
6522            (message-gnksa-enable-p 'cancel-messages)
6523            (and (setq sender (message-fetch-field "sender"))
6524                 (string-equal (downcase sender)
6525                               (downcase (message-make-sender))))
6526            ;; Email address in From field equals to our address
6527            (and (setq from (message-fetch-field "from"))
6528                 (string-equal
6529                  (downcase (cadr (std11-extract-address-components from)))
6530                  (downcase (cadr (std11-extract-address-components
6531                                   (message-make-from))))))
6532            ;; Email address in From field matches
6533            ;; 'message-alternative-emails' regexp
6534            (and from
6535                 message-alternative-emails
6536                 (string-match
6537                  message-alternative-emails
6538                  (cadr (std11-extract-address-components from))))))))))
6539
6540 ;;;###autoload
6541 (defun message-cancel-news (&optional arg)
6542   "Cancel an article you posted.
6543 If ARG, allow editing of the cancellation message."
6544   (interactive "P")
6545   (unless (message-news-p)
6546     (error "This is not a news article; canceling is impossible"))
6547   (let (from newsgroups message-id distribution buf)
6548     (save-excursion
6549       ;; Get header info from original article.
6550       (save-restriction
6551         (message-narrow-to-head-1)
6552         (setq from (message-fetch-field "from")
6553               newsgroups (message-fetch-field "newsgroups")
6554               message-id (message-fetch-field "message-id" t)
6555               distribution (message-fetch-field "distribution")))
6556       ;; Make sure that this article was written by the user.
6557       (unless (message-is-yours-p)
6558         (error "This article is not yours"))
6559       (when (yes-or-no-p "Do you really want to cancel this article? ")
6560         ;; Make control message.
6561         (if arg
6562             (message-news)
6563           (setq buf (set-buffer (get-buffer-create " *message cancel*"))))
6564         (erase-buffer)
6565         (insert "Newsgroups: " newsgroups "\n"
6566                 "From: " from "\n"
6567                 "Subject: cmsg cancel " message-id "\n"
6568                 "Control: cancel " message-id "\n"
6569                 (if distribution
6570                     (concat "Distribution: " distribution "\n")
6571                   "")
6572                 mail-header-separator "\n"
6573                 message-cancel-message)
6574         (run-hooks 'message-cancel-hook)
6575         (unless arg
6576           (message "Canceling your article...")
6577           (if (let ((message-syntax-checks
6578                      'dont-check-for-anything-just-trust-me)
6579                     (message-encoding-buffer (current-buffer))
6580                     (message-edit-buffer (current-buffer)))
6581                 (message-send-news))
6582               (message "Canceling your article...done"))
6583           (kill-buffer buf))))))
6584
6585 (defun message-supersede-setup-for-mime-edit ()
6586   (set (make-local-variable 'message-setup-hook) nil)
6587   (mime-edit-again))
6588
6589 ;;;###autoload
6590 (defun message-supersede ()
6591   "Start composing a message to supersede the current message.
6592 This is done simply by taking the old article and adding a Supersedes
6593 header line with the old Message-ID."
6594   (interactive)
6595   (let ((cur (current-buffer)))
6596     ;; Check whether the user owns the article that is to be superseded.
6597     (unless (message-is-yours-p)
6598       (error "This article is not yours"))
6599     ;; Get a normal message buffer.
6600     (message-pop-to-buffer (message-buffer-name "supersede"))
6601     (insert-buffer-substring cur)
6602     (message-narrow-to-head-1)
6603     ;; Remove unwanted headers.
6604     (when message-ignored-supersedes-headers
6605       (message-remove-header message-ignored-supersedes-headers t))
6606     (goto-char (point-min))
6607     (if (not (re-search-forward "^Message-ID: " nil t))
6608         (error "No Message-ID in this article")
6609       (replace-match "Supersedes: " t t))
6610     (goto-char (point-max))
6611     (insert mail-header-separator)
6612     (widen)
6613     (when message-supersede-setup-function
6614       (funcall message-supersede-setup-function))
6615     (run-hooks 'message-supersede-setup-hook)
6616     (goto-char (point-min))
6617     (search-forward (concat "\n" mail-header-separator "\n") nil t)))
6618
6619 ;;;###autoload
6620 (defun message-recover ()
6621   "Reread contents of current buffer from its last auto-save file."
6622   (interactive)
6623   (let ((file-name (make-auto-save-file-name)))
6624     (cond ((save-window-excursion
6625              (if (not (eq system-type 'vax-vms))
6626                  (with-output-to-temp-buffer "*Directory*"
6627                    (with-current-buffer standard-output
6628                      (fundamental-mode)) ; for Emacs 20.4+
6629                    (buffer-disable-undo standard-output)
6630                    (let ((default-directory "/"))
6631                      (call-process
6632                       "ls" nil standard-output nil "-l" file-name))))
6633              (yes-or-no-p (format "Recover auto save file %s? " file-name)))
6634            (let ((buffer-read-only nil))
6635              (erase-buffer)
6636              (insert-file-contents file-name nil)))
6637           (t (error "message-recover cancelled")))))
6638
6639 ;;; Washing Subject:
6640
6641 (defun message-wash-subject (subject)
6642   "Remove junk like \"Re:\", \"(fwd)\", etc. added to subject string SUBJECT.
6643 Previous forwarders, replyers, etc. may add it."
6644   (with-temp-buffer
6645     (insert subject)
6646     (goto-char (point-min))
6647     ;; strip Re/Fwd stuff off the beginning
6648     (while (re-search-forward
6649             "\\([Rr][Ee]:\\|[Ff][Ww][Dd]\\(\\[[0-9]*\\]\\)?:\\|[Ff][Ww]:\\)" nil t)
6650       (replace-match ""))
6651
6652     ;; and gnus-style forwards [foo@bar.com] subject
6653     (goto-char (point-min))
6654     (while (re-search-forward "\\[[^ \t]*\\(@\\|\\.\\)[^ \t]*\\]" nil t)
6655       (replace-match ""))
6656
6657     ;; and off the end
6658     (goto-char (point-max))
6659     (while (re-search-backward "([Ff][Ww][Dd])" nil t)
6660       (replace-match ""))
6661
6662     ;; and finally, any whitespace that was left-over
6663     (goto-char (point-min))
6664     (while (re-search-forward "^[ \t]+" nil t)
6665       (replace-match ""))
6666     (goto-char (point-max))
6667     (while (re-search-backward "[ \t]+$" nil t)
6668       (replace-match ""))
6669
6670     (buffer-string)))
6671
6672 ;;; Forwarding messages.
6673
6674 (defvar message-forward-decoded-p nil
6675   "Non-nil means the original message is decoded.")
6676
6677 (defun message-forward-subject-name-subject (subject)
6678   "Generate a SUBJECT for a forwarded message.
6679 The form is: [Source] Subject, where if the original message was mail,
6680 Source is the name of the sender, and if the original message was
6681 news, Source is the list of newsgroups is was posted to."
6682   (concat "["
6683           (let ((group (message-fetch-field "newsgroups"))
6684                 from)
6685             (if group
6686                 (gnus-group-decoded-name group)
6687               (or (and (setq from (message-fetch-field "from"))
6688                        (car (std11-extract-address-components 
6689                              (nnheader-decode-from from))))
6690                   "(nowhere)")))
6691           "] " subject))
6692
6693 (defun message-forward-subject-author-subject (subject)
6694   "Generate a SUBJECT for a forwarded message.
6695 The form is: [Source] Subject, where if the original message was mail,
6696 Source is the sender, and if the original message was news, Source is
6697 the list of newsgroups is was posted to."
6698   (concat "["
6699           (let ((group (message-fetch-field "newsgroups"))
6700                 from)
6701             (if group
6702                 (gnus-group-decoded-name group)
6703               (if (setq from (message-fetch-field "from"))
6704                   (nnheader-decode-from from)
6705                 "(nowhere)")))
6706           "] " subject))
6707
6708 (defun message-forward-subject-fwd (subject)
6709   "Generate a SUBJECT for a forwarded message.
6710 The form is: Fwd: Subject, where Subject is the original subject of
6711 the message."
6712   (if (string-match "^Fwd: " subject)
6713       subject
6714     (concat "Fwd: " subject)))
6715
6716 (defun message-make-forward-subject ()
6717   "Return a Subject header suitable for the message in the current buffer."
6718   (save-excursion
6719     (save-restriction
6720       (message-narrow-to-head-1)
6721       (let ((funcs message-make-forward-subject-function)
6722             (subject (message-fetch-field "Subject")))
6723         (setq subject
6724               (if subject
6725                   (if message-forward-decoded-p
6726                       subject
6727                     (nnheader-decode-subject subject))
6728                 ""))
6729         (if message-wash-forwarded-subjects
6730             (setq subject (message-wash-subject subject)))
6731         ;; Make sure funcs is a list.
6732         (and funcs
6733              (not (listp funcs))
6734              (setq funcs (list funcs)))
6735         ;; Apply funcs in order, passing subject generated by previous
6736         ;; func to the next one.
6737         (while funcs
6738           (when (functionp (car funcs))
6739             (setq subject (funcall (car funcs) subject)))
6740           (setq funcs (cdr funcs)))
6741         subject))))
6742
6743 ;;;###autoload
6744 (defun message-forward (&optional news)
6745   "Forward the current message via mail.
6746 Optional NEWS will use news to forward instead of mail."
6747   (interactive "P")
6748   (let ((cur (current-buffer))
6749         (subject (message-make-forward-subject)))
6750     (if news
6751         (message-news nil subject)
6752       (message-mail nil subject))
6753     (message-forward-make-body cur)))
6754
6755 (defun message-forward-make-body-plain (forward-buffer)
6756   (insert
6757    "\n-------------------- Start of forwarded message --------------------\n")
6758   (let ((b (point)) e)
6759     (insert
6760      (with-temp-buffer
6761        (mm-disable-multibyte)
6762        (insert
6763         (with-current-buffer forward-buffer
6764           (mm-with-unibyte-current-buffer (buffer-string))))
6765        (mm-enable-multibyte)
6766        (mime-to-mml)
6767        (goto-char (point-min))
6768        (when (looking-at "From ")
6769          (replace-match "X-From-Line: "))
6770        (buffer-string)))
6771     (setq e (point))
6772     (insert
6773      "\n-------------------- End of forwarded message --------------------\n")
6774     (when (and (not current-prefix-arg)
6775                message-forward-ignored-headers)
6776       (save-restriction
6777         (narrow-to-region b e)
6778         (goto-char b)
6779         (narrow-to-region (point)
6780                           (or (search-forward "\n\n" nil t) (point)))
6781         (message-remove-header message-forward-ignored-headers t)))))
6782
6783 (defun message-forward-make-body-mime (forward-buffer)
6784   (insert "\n\n<#part type=message/rfc822 disposition=inline raw=t>\n")
6785   (let ((b (point)) e)
6786     (save-restriction
6787       (narrow-to-region (point) (point))
6788       (mml-insert-buffer forward-buffer)
6789       (goto-char (point-min))
6790       (when (looking-at "From ")
6791         (replace-match "X-From-Line: "))
6792       (goto-char (point-max)))
6793     (setq e (point))
6794     (insert "<#/part>\n")))
6795
6796 (defun message-forward-make-body-mml (forward-buffer)
6797   (insert "\n\n<#mml type=message/rfc822 disposition=inline>\n")
6798   (let ((b (point)) e)
6799     (if (not message-forward-decoded-p)
6800         (insert
6801          (with-temp-buffer
6802            (mm-disable-multibyte)
6803            (insert
6804             (with-current-buffer forward-buffer
6805               (mm-with-unibyte-current-buffer (buffer-string))))
6806            (mm-enable-multibyte)
6807            (mime-to-mml)
6808            (goto-char (point-min))
6809            (when (looking-at "From ")
6810              (replace-match "X-From-Line: "))
6811            (buffer-string)))
6812       (save-restriction
6813         (narrow-to-region (point) (point))
6814         (mml-insert-buffer forward-buffer)
6815         (goto-char (point-min))
6816         (when (looking-at "From ")
6817           (replace-match "X-From-Line: "))
6818         (goto-char (point-max))))
6819     (setq e (point))
6820     (insert "<#/mml>\n")
6821     (when (and (not current-prefix-arg)
6822                message-forward-ignored-headers)
6823       (save-restriction
6824         (narrow-to-region b e)
6825         (goto-char b)
6826         (narrow-to-region (point)
6827                           (or (search-forward "\n\n" nil t) (point)))
6828         (message-remove-header message-forward-ignored-headers t)))))
6829
6830 (defun message-forward-make-body-digest-plain (forward-buffer)
6831   (insert
6832    "\n-------------------- Start of forwarded message --------------------\n")
6833   (let ((b (point)) e)
6834     (mml-insert-buffer forward-buffer)
6835     (setq e (point))
6836     (insert
6837      "\n-------------------- End of forwarded message --------------------\n")))
6838
6839 (defun message-forward-make-body-digest-mime (forward-buffer)
6840   (insert "\n<#multipart type=digest>\n")
6841   (let ((b (point)) e)
6842     (insert-buffer-substring forward-buffer)
6843     (setq e (point))
6844     (insert "<#/multipart>\n")
6845     (save-restriction
6846       (narrow-to-region b e)
6847       (goto-char b)
6848       (narrow-to-region (point)
6849                         (or (search-forward "\n\n" nil t) (point)))
6850       (delete-region (point-min) (point-max)))))
6851
6852 (defun message-forward-make-body-digest (forward-buffer)
6853   (if message-forward-as-mime
6854       (message-forward-make-body-digest-mime forward-buffer)
6855     (message-forward-make-body-digest-plain forward-buffer)))
6856
6857 ;;;###autoload
6858 (defun message-forward-make-body (forward-buffer)
6859   ;; Put point where we want it before inserting the forwarded
6860   ;; message.
6861   ;; Note that this function definition for T-gnus is totally different
6862   ;; from the original Gnus."
6863   (if message-forward-before-signature
6864       (message-goto-body)
6865     (goto-char (point-max)))
6866   ;; Make sure we're at the start of the line.
6867   (unless (bolp)
6868     (insert "\n"))
6869   ;; Narrow to the area we are to insert.
6870   (narrow-to-region (point) (point))
6871   ;; Insert the separators and the forwarded buffer.
6872   (insert message-forward-start-separator)
6873   (let ((art-beg (point)))
6874     (insert-buffer-substring forward-buffer)
6875     (goto-char (point-max))
6876     (insert message-forward-end-separator)
6877     (set-text-properties (point-min) (point-max) nil)
6878     ;; Remove all unwanted headers.
6879     (goto-char art-beg)
6880     (narrow-to-region (point) (if (search-forward "\n\n" nil t)
6881                                   (1- (point))
6882                                 (point)))
6883     (goto-char (point-min))
6884     (message-remove-header message-included-forward-headers t nil t)
6885     (widen)
6886     (message-position-point)))
6887
6888 ;;;###autoload
6889 (defun message-forward-rmail-make-body (forward-buffer)
6890   (save-window-excursion
6891     (set-buffer forward-buffer)
6892     ;; Rmail doesn't have rmail-msg-restore-non-pruned-header in Emacs
6893     ;; 20.  FIXIT, or we drop support for rmail in Emacs 20.
6894     (if (rmail-msg-is-pruned)
6895         (rmail-msg-restore-non-pruned-header)))
6896   (message-forward-make-body forward-buffer))
6897
6898 (eval-when-compile (defvar rmail-enable-mime-composing))
6899
6900 ;; Fixme: Should have defcustom.
6901 ;;;###autoload
6902 (defun message-insinuate-rmail ()
6903   "Let RMAIL use message to forward."
6904   (interactive)
6905   (setq rmail-enable-mime-composing t)
6906   (setq rmail-insert-mime-forwarded-message-function
6907         'message-forward-rmail-make-body))
6908
6909 ;;;###autoload
6910 (defun message-resend (address)
6911   "Resend the current article to ADDRESS."
6912   (interactive
6913    (list (message-read-from-minibuffer "Resend message to: ")))
6914   (message "Resending message to %s..." address)
6915   (save-excursion
6916     (let ((cur (current-buffer))
6917           beg)
6918       ;; We first set up a normal mail buffer.
6919       (unless (message-mail-user-agent)
6920         (set-buffer (get-buffer-create " *message resend*"))
6921         (erase-buffer))
6922       (let ((message-this-is-mail t)
6923             message-setup-hook)
6924         (message-setup `((To . ,address))))
6925       ;; Insert our usual headers.
6926       (message-generate-headers '(From Date To Message-ID))
6927       (message-narrow-to-headers)
6928       ;; Remove X-Draft-From header etc.
6929       (message-remove-header message-ignored-mail-headers t)
6930       ;; Rename them all to "Resent-*".
6931       (goto-char (point-min))
6932       (while (re-search-forward "^[A-Za-z]" nil t)
6933         (forward-char -1)
6934         (insert "Resent-"))
6935       (widen)
6936       (forward-line)
6937       (delete-region (point) (point-max))
6938       (setq beg (point))
6939       ;; Insert the message to be resent.
6940       (insert-buffer-substring cur)
6941       (goto-char (point-min))
6942       (search-forward "\n\n")
6943       (forward-char -1)
6944       (save-restriction
6945         (narrow-to-region beg (point))
6946         (message-remove-header message-ignored-resent-headers t)
6947         (goto-char (point-max)))
6948       (insert mail-header-separator)
6949       ;; Rename all old ("Also-")Resent headers.
6950       (while (re-search-backward "^\\(Also-\\)*Resent-" beg t)
6951         (beginning-of-line)
6952         (insert "Also-"))
6953       ;; Quote any "From " lines at the beginning.
6954       (goto-char beg)
6955       (when (looking-at "From ")
6956         (replace-match "X-From-Line: "))
6957       ;; Send it.
6958       (let ((message-encoding-buffer (current-buffer))
6959             (message-edit-buffer (current-buffer))
6960             message-required-mail-headers)
6961         (message-send-mail))
6962       (kill-buffer (current-buffer)))
6963     (message "Resending message to %s...done" address)))
6964
6965 (defun message-bounce-setup-for-mime-edit ()
6966   (set (make-local-variable 'message-setup-hook) nil)
6967   (mime-edit-again))
6968
6969 ;;;###autoload
6970 (defun message-bounce ()
6971   "Re-mail the current message.
6972 This only makes sense if the current message is a bounce message that
6973 contains some mail you have written which has been bounced back to
6974 you."
6975   (interactive)
6976   (let ((cur (current-buffer))
6977         mime-boundary boundary)
6978     (message-pop-to-buffer (message-buffer-name "bounce"))
6979     (insert-buffer-substring cur)
6980     (undo-boundary)
6981     (message-narrow-to-head)
6982     (if (and (message-fetch-field "MIME-Version")
6983              (setq mime-boundary (message-fetch-field "Content-Type")))
6984         (if (string-match "boundary=\"\\([^\"]+\\)\"" mime-boundary)
6985             (setq mime-boundary (concat (regexp-quote
6986                                          (match-string 1 mime-boundary))
6987                                         " *\nContent-Type: message/rfc822"))
6988           (setq mime-boundary nil)))
6989     (widen)
6990     (goto-char (point-min))
6991     (re-search-forward "\n\n+" nil t)
6992     (setq boundary (point))
6993     ;; We remove everything before the bounced mail.
6994     (if (or (and mime-boundary
6995                  (re-search-forward mime-boundary nil t)
6996                  (forward-line 1))
6997             (re-search-forward message-unsent-separator nil t)
6998             (progn
6999               (search-forward "\n\n" nil 'move)
7000               (re-search-backward "^Return-Path:.*\n" boundary t)))
7001         (progn
7002           (forward-line 1)
7003           (delete-region (point-min)
7004                          (if (re-search-forward "^[^ \n\t]+:" nil t)
7005                              (match-beginning 0)
7006                            (point))))
7007       (when (re-search-backward "^.?From .*\n" nil t)
7008         (delete-region (match-beginning 0) (match-end 0))))
7009     (save-restriction
7010       (message-narrow-to-head-1)
7011       (message-remove-header message-ignored-bounced-headers t)
7012       (goto-char (point-max))
7013       (insert mail-header-separator))
7014     (when message-bounce-setup-function
7015       (funcall message-bounce-setup-function))
7016     (run-hooks 'message-bounce-setup-hook)
7017     (message-position-point)))
7018
7019 ;;;
7020 ;;; Interactive entry points for new message buffers.
7021 ;;;
7022
7023 ;;;###autoload
7024 (defun message-mail-other-window (&optional to subject)
7025   "Like `message-mail' command, but display mail buffer in another window."
7026   (interactive)
7027   (unless (message-mail-user-agent)
7028     (let ((pop-up-windows t)
7029           (special-display-buffer-names nil)
7030           (special-display-regexps nil)
7031           (same-window-buffer-names nil)
7032           (same-window-regexps nil))
7033       (message-pop-to-buffer (message-buffer-name "mail" to))))
7034   (let ((message-this-is-mail t))
7035     (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))
7036                    nil nil 'switch-to-buffer-other-window)))
7037
7038 ;;;###autoload
7039 (defun message-mail-other-frame (&optional to subject)
7040   "Like `message-mail' command, but display mail buffer in another frame."
7041   (interactive)
7042   (unless (message-mail-user-agent)
7043     (let ((pop-up-frames t)
7044           (special-display-buffer-names nil)
7045           (special-display-regexps nil)
7046           (same-window-buffer-names nil)
7047           (same-window-regexps nil))
7048       (message-pop-to-buffer (message-buffer-name "mail" to))))
7049   (let ((message-this-is-mail t))
7050     (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))
7051                    nil nil 'switch-to-buffer-other-frame)))
7052
7053 ;;;###autoload
7054 (defun message-news-other-window (&optional newsgroups subject)
7055   "Start editing a news article to be sent."
7056   (interactive)
7057   (let ((pop-up-windows t)
7058         (special-display-buffer-names nil)
7059         (special-display-regexps nil)
7060         (same-window-buffer-names nil)
7061         (same-window-regexps nil))
7062     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups)))
7063   (let ((message-this-is-news t))
7064     (message-setup `((Newsgroups . ,(or newsgroups ""))
7065                      (Subject . ,(or subject ""))))))
7066
7067 ;;;###autoload
7068 (defun message-news-other-frame (&optional newsgroups subject)
7069   "Start editing a news article to be sent."
7070   (interactive)
7071   (let ((pop-up-frames t)
7072         (special-display-buffer-names nil)
7073         (special-display-regexps nil)
7074         (same-window-buffer-names nil)
7075         (same-window-regexps nil))
7076     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups)))
7077   (let ((message-this-is-news t))
7078     (message-setup `((Newsgroups . ,(or newsgroups ""))
7079                      (Subject . ,(or subject ""))))))
7080
7081 ;;; underline.el
7082
7083 ;; This code should be moved to underline.el (from which it is stolen).
7084
7085 ;;;###autoload
7086 (defun bold-region (start end)
7087   "Bold all nonblank characters in the region.
7088 Works by overstriking characters.
7089 Called from program, takes two arguments START and END
7090 which specify the range to operate on."
7091   (interactive "r")
7092   (save-excursion
7093     (let ((end1 (make-marker)))
7094       (move-marker end1 (max start end))
7095       (goto-char (min start end))
7096       (while (< (point) end1)
7097         (or (looking-at "[_\^@- ]")
7098             (insert (char-after) "\b"))
7099         (forward-char 1)))))
7100
7101 ;;;###autoload
7102 (defun unbold-region (start end)
7103   "Remove all boldness (overstruck characters) in the region.
7104 Called from program, takes two arguments START and END
7105 which specify the range to operate on."
7106   (interactive "r")
7107   (save-excursion
7108     (let ((end1 (make-marker)))
7109       (move-marker end1 (max start end))
7110       (goto-char (min start end))
7111       (while (re-search-forward "\b" end1 t)
7112         (if (eq (char-after) (char-after (- (point) 2)))
7113             (delete-char -2))))))
7114
7115 (defalias 'message-exchange-point-and-mark 'exchange-point-and-mark)
7116 (defalias 'message-make-overlay 'make-overlay)
7117 (defalias 'message-delete-overlay 'delete-overlay)
7118 (defalias 'message-overlay-put 'overlay-put)
7119 (defun message-kill-all-overlays ()
7120   (if (featurep 'xemacs)
7121       (map-extents (lambda (extent ignore) (delete-extent extent)))
7122     (mapcar #'delete-overlay (overlays-in (point-min) (point-max)))))
7123
7124 ;; Support for toolbar
7125 (eval-when-compile
7126   (defvar tool-bar-map)
7127   (defvar tool-bar-mode))
7128
7129 (defun message-tool-bar-local-item-from-menu (command icon in-map &optional from-map &rest props)
7130   ;; We need to make tool bar entries in local keymaps with
7131   ;; `tool-bar-local-item-from-menu' in Emacs > 21.3
7132   (if (fboundp 'tool-bar-local-item-from-menu)
7133       ;; This is for Emacs 21.3
7134       (tool-bar-local-item-from-menu command icon in-map from-map props)
7135     (tool-bar-add-item-from-menu command icon from-map props)))
7136
7137 (defun message-tool-bar-map ()
7138   (or message-tool-bar-map
7139       (setq message-tool-bar-map
7140             (and
7141              (condition-case nil (require 'tool-bar) (error nil))
7142              (fboundp 'tool-bar-add-item-from-menu)
7143              tool-bar-mode
7144              (let ((tool-bar-map (copy-keymap tool-bar-map))
7145                    (load-path (mm-image-load-path)))
7146                ;; Zap some items which aren't so relevant and take
7147                ;; up space.
7148                (dolist (key '(print-buffer kill-buffer save-buffer
7149                                            write-file dired open-file))
7150                  (define-key tool-bar-map (vector key) nil))
7151                (message-tool-bar-local-item-from-menu
7152                 'message-send-and-exit "mail_send" tool-bar-map message-mode-map)
7153                (message-tool-bar-local-item-from-menu
7154                 'message-kill-buffer "close" tool-bar-map message-mode-map)
7155                (message-tool-bar-local-item-from-menu
7156                 'message-dont-send "cancel" tool-bar-map message-mode-map)
7157 ;;             (message-tool-bar-local-item-from-menu
7158 ;;              'mime-edit-insert-file "attach"
7159 ;;              tool-bar-map mime-edit-mode-map)
7160                (message-tool-bar-local-item-from-menu
7161                 'ispell-message "spell" tool-bar-map message-mode-map)
7162 ;;             (message-tool-bar-local-item-from-menu
7163 ;;              'mime-edit-preview-message "preview"
7164 ;;              tool-bar-map mime-edit-mode-map)
7165                (message-tool-bar-local-item-from-menu
7166                 'message-insert-importance-high "important"
7167                 tool-bar-map message-mode-map)
7168                (message-tool-bar-local-item-from-menu
7169                 'message-insert-importance-low "unimportant"
7170                 tool-bar-map message-mode-map)
7171                (message-tool-bar-local-item-from-menu
7172                 'message-insert-disposition-notification-to "receipt"
7173                 tool-bar-map message-mode-map)
7174                tool-bar-map)))))
7175
7176 ;;; Group name completion.
7177
7178 (defcustom message-newgroups-header-regexp
7179   "^\\(Newsgroups\\|Followup-To\\|Posted-To\\|Gcc\\):"
7180   "Regexp that match headers that lists groups."
7181   :group 'message
7182   :type 'regexp)
7183
7184 (defcustom message-completion-alist
7185   (list (cons message-newgroups-header-regexp 'message-expand-group)
7186         '("^\\(Resent-\\)?\\(To\\|B?Cc\\):" . message-expand-name)
7187         '("^\\(Reply-To\\|From\\|Mail-Followup-To\\|Mail-Copies-To\\):"
7188           . message-expand-name)
7189         '("^\\(Disposition-Notification-To\\|Return-Receipt-To\\):"
7190           . message-expand-name))
7191   "Alist of (RE . FUN).  Use FUN for completion on header lines matching RE."
7192   :group 'message
7193   :type '(alist :key-type regexp :value-type function))
7194
7195 (defcustom message-expand-name-function
7196   (if (fboundp 'bbdb-complete-name)
7197       'bbdb-complete-name
7198     (if (fboundp 'lsdb-complete-name)
7199         'lsdb-complete-name
7200       'expand-abbrev))
7201   "*A function called to expand addresses in field body."
7202   :group 'message
7203   :type 'function)
7204
7205 (defcustom message-tab-body-function nil
7206   "*Function to execute when `message-tab' (TAB) is executed in the body.
7207 If nil, the function bound in `text-mode-map' or `global-map' is executed."
7208   :group 'message
7209   :type 'function)
7210
7211 (defun message-tab ()
7212   "Complete names according to `message-completion-alist'.
7213 Execute function specified by `message-tab-body-function' when not in
7214 those headers."
7215   (interactive)
7216   (let ((alist message-completion-alist))
7217     (while (and alist
7218                 (let ((mail-abbrev-mode-regexp (caar alist)))
7219                   (not (mail-abbrev-in-expansion-header-p))))
7220       (setq alist (cdr alist)))
7221     (funcall (or (cdar alist) message-tab-body-function
7222                  (lookup-key text-mode-map "\t")
7223                  (lookup-key global-map "\t")
7224                  'indent-relative))))
7225
7226 (defun message-expand-group ()
7227   "Expand the group name under point."
7228   (let* ((b (save-excursion
7229               (save-restriction
7230                 (narrow-to-region
7231                  (save-excursion
7232                    (beginning-of-line)
7233                    (skip-chars-forward "^:")
7234                    (1+ (point)))
7235                  (point))
7236                 (skip-chars-backward "^, \t\n") (point))))
7237          (completion-ignore-case t)
7238          (string (buffer-substring b (progn (skip-chars-forward "^,\t\n ")
7239                                             (point))))
7240          (hashtb (and (boundp 'gnus-active-hashtb) gnus-active-hashtb))
7241          (completions (all-completions string hashtb))
7242          comp)
7243     (delete-region b (point))
7244     (cond
7245      ((= (length completions) 1)
7246       (if (string= (car completions) string)
7247           (progn
7248             (insert string)
7249             (message "Only matching group"))
7250         (insert (car completions))))
7251      ((and (setq comp (try-completion string hashtb))
7252            (not (string= comp string)))
7253       (insert comp))
7254      (t
7255       (insert string)
7256       (if (not comp)
7257           (message "No matching groups")
7258         (save-selected-window
7259           (pop-to-buffer "*Completions*")
7260           (buffer-disable-undo)
7261           (let ((buffer-read-only nil))
7262             (erase-buffer)
7263             (let ((standard-output (current-buffer)))
7264               (display-completion-list (sort completions 'string<)))
7265             (goto-char (point-min))
7266             (delete-region (point) (progn (forward-line 3) (point))))))))))
7267
7268 (defun message-expand-name ()
7269   (funcall message-expand-name-function))
7270
7271 ;;; Help stuff.
7272
7273 (defun message-talkative-question (ask question show &rest text)
7274   "Call FUNCTION with argument QUESTION; optionally display TEXT... args.
7275 If SHOW is non-nil, the arguments TEXT... are displayed in a temp buffer.
7276 The following arguments may contain lists of values."
7277   (if (and show
7278            (setq text (message-flatten-list text)))
7279       (save-window-excursion
7280         (save-excursion
7281           (with-output-to-temp-buffer " *MESSAGE information message*"
7282             (set-buffer " *MESSAGE information message*")
7283             (fundamental-mode)          ; for Emacs 20.4+
7284             (mapcar 'princ text)
7285             (goto-char (point-min))))
7286         (funcall ask question))
7287     (funcall ask question)))
7288
7289 (defun message-flatten-list (list)
7290   "Return a new, flat list that contains all elements of LIST.
7291
7292 \(message-flatten-list '(1 (2 3 (4 5 (6))) 7))
7293 => (1 2 3 4 5 6 7)"
7294   (cond ((consp list)
7295          (apply 'append (mapcar 'message-flatten-list list)))
7296         (list
7297          (list list))))
7298
7299 (defun message-generate-new-buffer-clone-locals (name &optional varstr)
7300   "Create and return a buffer with name based on NAME using `generate-new-buffer'.
7301 Then clone the local variables and values from the old buffer to the
7302 new one, cloning only the locals having a substring matching the
7303 regexp VARSTR."
7304   (let ((oldbuf (current-buffer)))
7305     (save-excursion
7306       (set-buffer (generate-new-buffer name))
7307       (message-clone-locals oldbuf varstr)
7308       (current-buffer))))
7309
7310 (defun message-clone-locals (buffer &optional varstr)
7311   "Clone the local variables from BUFFER to the current buffer."
7312   (let ((locals (save-excursion
7313                   (set-buffer buffer)
7314                   (buffer-local-variables)))
7315         (regexp
7316          "^\\(gnus\\|nn\\|message\\|user-\\(mail-address\\|full-name\\)\\)"))
7317     (mapcar
7318      (lambda (local)
7319        (when (and (consp local)
7320                   (car local)
7321                   (string-match regexp (symbol-name (car local)))
7322                   (or (null varstr)
7323                       (string-match varstr (symbol-name (car local)))))
7324          (ignore-errors
7325            (set (make-local-variable (car local))
7326                 (cdr local)))))
7327      locals)))
7328
7329 ;;; @ for MIME Edit mode
7330 ;;;
7331
7332 (defun message-maybe-encode ()
7333   (when message-mime-mode
7334     ;; Inherit the buffer local variable `mime-edit-pgp-processing'.
7335     (let ((pgp-processing (with-current-buffer message-edit-buffer
7336                             mime-edit-pgp-processing)))
7337       (setq mime-edit-pgp-processing pgp-processing))
7338     (run-hooks 'mime-edit-translate-hook)
7339     (if (catch 'mime-edit-error
7340           (save-excursion
7341             (mime-edit-pgp-enclose-buffer)
7342             (mime-edit-translate-body)))
7343         (error "Translation error!"))
7344     (run-hooks 'mime-edit-exit-hook)))
7345
7346 (defun message-mime-insert-article (&optional full-headers)
7347   (interactive "P")
7348   (let ((message-cite-function 'mime-edit-inserted-message-filter)
7349         (message-reply-buffer
7350          (message-get-parameter-with-eval 'original-buffer))
7351         (start (point)))
7352     (message-yank-original nil)
7353     (save-excursion
7354       (narrow-to-region (goto-char start)
7355                         (if (search-forward "\n\n" nil t)
7356                             (1- (point))
7357                           (point-max)))
7358       (goto-char (point-min))
7359       (let ((message-included-forward-headers
7360              (if full-headers "" message-included-forward-headers)))
7361         (message-remove-header message-included-forward-headers t nil t))
7362       (widen))))
7363
7364 (set-alist 'mime-edit-message-inserter-alist
7365            'message-mode (function message-mime-insert-article))
7366
7367 ;;;
7368 ;;; MIME functions
7369 ;;;
7370
7371 (defvar message-inhibit-body-encoding t)
7372
7373 (defun message-encode-message-body ()
7374   (unless message-inhibit-body-encoding
7375     (let ((mail-parse-charset (or mail-parse-charset
7376                                   message-default-charset))
7377           (case-fold-search t)
7378           lines content-type-p)
7379       (message-goto-body)
7380       (save-restriction
7381         (narrow-to-region (point) (point-max))
7382         (let ((new (mml-generate-mime)))
7383           (when new
7384             (delete-region (point-min) (point-max))
7385             (insert new)
7386             (goto-char (point-min))
7387             (if (eq (aref new 0) ?\n)
7388                 (delete-char 1)
7389               (search-forward "\n\n")
7390               (setq lines (buffer-substring (point-min) (1- (point))))
7391               (delete-region (point-min) (point))))))
7392       (save-restriction
7393         (message-narrow-to-headers-or-head)
7394         (message-remove-header "Mime-Version")
7395         (goto-char (point-max))
7396         (insert "MIME-Version: 1.0\n")
7397         (when lines
7398           (insert lines))
7399         (setq content-type-p
7400               (or mml-boundary
7401                   (re-search-backward "^Content-Type:" nil t))))
7402       (save-restriction
7403         (message-narrow-to-headers-or-head)
7404         (message-remove-first-header "Content-Type")
7405         (message-remove-first-header "Content-Transfer-Encoding"))
7406       ;; We always make sure that the message has a Content-Type
7407       ;; header.  This is because some broken MTAs and MUAs get
7408       ;; awfully confused when confronted with a message with a
7409       ;; MIME-Version header and without a Content-Type header.  For
7410       ;; instance, Solaris' /usr/bin/mail.
7411       (unless content-type-p
7412         (goto-char (point-min))
7413         ;; For unknown reason, MIME-Version doesn't exist.
7414         (when (re-search-forward "^MIME-Version:" nil t)
7415           (forward-line 1)
7416           (insert "Content-Type: text/plain; charset=us-ascii\n"))))))
7417
7418 (defun message-read-from-minibuffer (prompt &optional initial-contents)
7419   "Read from the minibuffer while providing abbrev expansion."
7420   (if (fboundp 'mail-abbrevs-setup)
7421       (let ((mail-abbrev-mode-regexp "")
7422             (minibuffer-setup-hook 'mail-abbrevs-setup)
7423             (minibuffer-local-map message-minibuffer-local-map))
7424         (read-from-minibuffer prompt initial-contents))
7425     (let ((minibuffer-setup-hook 'mail-abbrev-minibuffer-setup-hook)
7426           (minibuffer-local-map message-minibuffer-local-map))
7427       (read-string prompt initial-contents))))
7428
7429 (defun message-use-alternative-email-as-from ()
7430   (require 'mail-utils)
7431   (let* ((fields '("To" "Cc"))
7432          (emails
7433           (split-string
7434            (mail-strip-quoted-names
7435             (mapconcat 'message-fetch-reply-field fields ","))
7436            "[ \f\t\n\r\v,]+"))
7437          email)
7438     (while emails
7439       (if (string-match message-alternative-emails (car emails))
7440           (setq email (car emails)
7441                 emails nil))
7442       (pop emails))
7443     (unless (or (not email) (equal email user-mail-address))
7444       (goto-char (point-max))
7445       (insert "From: " email "\n"))))
7446
7447 (defun message-options-get (symbol)
7448   (cdr (assq symbol message-options)))
7449
7450 (defun message-options-set (symbol value)
7451   (let ((the-cons (assq symbol message-options)))
7452     (if the-cons
7453         (if value
7454             (setcdr the-cons value)
7455           (setq message-options (delq the-cons message-options)))
7456       (and value
7457            (push (cons symbol value) message-options))))
7458   value)
7459
7460 (defun message-options-set-recipient ()
7461   (save-restriction
7462     (message-narrow-to-headers-or-head)
7463     (message-options-set 'message-sender
7464                          (mail-strip-quoted-names
7465                           (message-fetch-field "from")))
7466     (message-options-set 'message-recipients
7467                          (mail-strip-quoted-names
7468                           (let ((to (message-fetch-field "to"))
7469                                 (cc (message-fetch-field "cc"))
7470                                 (bcc (message-fetch-field "bcc")))
7471                             (concat
7472                              (or to "")
7473                              (if (and to cc) ", ")
7474                              (or cc "")
7475                              (if (and (or to cc) bcc) ", ")
7476                              (or bcc "")))))))
7477
7478 (defun message-hide-headers ()
7479   "Hide headers based on the `message-hidden-headers' variable."
7480   (let ((regexps (if (stringp message-hidden-headers)
7481                      (list message-hidden-headers)
7482                    message-hidden-headers))
7483         (inhibit-point-motion-hooks t)
7484         (after-change-functions nil))
7485     (when regexps
7486       (save-excursion
7487         (save-restriction
7488           (message-narrow-to-headers)
7489           (goto-char (point-min))
7490           (while (not (eobp))
7491             (if (not (message-hide-header-p regexps))
7492                 (message-next-header)
7493               (let ((begin (point)))
7494                 (message-next-header)
7495                 (add-text-properties
7496                  begin (point)
7497                  '(invisible t message-hidden t))))))))))
7498
7499 (defun message-hide-header-p (regexps)
7500   (let ((result nil)
7501         (reverse nil))
7502     (when (eq (car regexps) 'not)
7503       (setq reverse t)
7504       (pop regexps))
7505     (dolist (regexp regexps)
7506       (setq result (or result (looking-at regexp))))
7507     (if reverse
7508         (not result)
7509       result)))
7510
7511 (when (featurep 'xemacs)
7512   (require 'messagexmas)
7513   (message-xmas-redefine))
7514
7515 (provide 'message)
7516
7517 (run-hooks 'message-load-hook)
7518
7519 ;; Local Variables:
7520 ;; coding: iso-8859-1
7521 ;; End:
7522
7523 ;;; message.el ends here