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