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