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