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