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