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