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