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