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