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