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