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